<?php
App::import('Sanitize');
class ProductsController extends AppController {
	var $name = 'Products';
	var $uses = array('Product','Note','User','Category','Categorybrand','Brand','Imagetitle','ProductImage','Field','ProductAdditionalFieldValue','Sizetitle','Sizevalue','ProductSize','Shipping','HandleTime','ProductShipping','Country','ProductInternationalShipping','Sizelabel');
	var $components = array('Uploader.Uploader','Email');
	var $helpers = array('Thumbnail','Csv','Fck');
	
	function beforeFilter(){
		parent::beforeFilter();
	  	$this->Auth->allowedActions = array('autobrand','brandnamebyid','viewdispute','breadcrumchkHasParent','color_menu','size_menu','gallery_popup','deletethumbimage','fetchadditionalfields_details','fetch_labels_fields_details','store','report_problem','details','advance_search','search_result','browsebycategory','feedback_chk_byuser','getnamebyid','brand_menu','browsebybrand','browsebycompletedlist','browsebyprice','browsebysize','browsebycolor','fetchsizes_edit','fetchadditionalfields_details_label');
		//fill with associated array of name, type, size to the corresponding column name
		$this->Uploader->uploadDir = 'img/uploads/';
		$this->Uploader->enableUpload = true;
		$this->Uploader->maxFileSize ='1M'; // 1 Megabytes
		$this->Uploader->maxNameLength=50;
		$this->Uploader->tempDir = TMP;
		$this->Uploader->mime('image','gif','image/gif');
	}
        
	function index() {
                $this->Product->recursive = -1;
		$this->paginate = array('limit' =>25,'conditions'=>array('Product.user_id'=>$this->Auth->User('id'),
                    'OR'=>array(array('Product.products_status'=>'Active'),array('Product.products_status'=>'Approved'))),'order' => array('Product.id' => 'desc'));
		//left nav
		$this->set('item', $this->Category->categoryArray());
		$this->set('products', $this->paginate());
		$this->layout="innerhome";
	}
        
	function add() {
		$this->layout="innerhome";
		
		if (!empty($this->data)) {
		//$this->data = Sanitize::clean($this->data, array('remove_html' => true));
		$this->Product->set($this->data);
		if ($this->Product->validates()){
			//uploading products image then add products
            if($data = $this->Uploader->uploadAll()){
                // Upload successful
				$this->data['Product']['products_thumbnailImage']=$data['fileName']['name'];
				
				if(empty($this->data['Product']['global_brands'])){
					$this->data['Product']['global_brands']=0;
				}
				//if user suggested new brand
				if(isset($this->data['Product']['sugestbrands']) AND empty($this->data['Product']['global_brands'])){
					$this->data['Brand']['brand_type']="brand";
					$this->data['Brand']['brand_description']=$this->data['Product']['sugestbrands'];
					$this->Brand->create();
					$this->Brand->save($this->data['Brand']);
					$brand_id=$this->Brand->getlastinsertid();
					$this->data['Categorybrand']['brand_type']="brand";
					$this->data['Categorybrand']['brand_id']=$brand_id;
					$this->data['Categorybrand']['category_id']=$this->data['Product']['category_id'];					
					$this->Categorybrand->create();
					$this->Categorybrand->save($this->data['Categorybrand']);
					$this->data['Product']['global_brands']=$brand_id;
				}
				
				if(empty($this->data['Product']['global_styles'])){
					$this->data['Product']['global_styles']=0;
				}
				//if user suggested new style
				if(isset($this->data['Product']['sugeststyles']) AND empty($this->data['Product']['global_styles'])){
					$this->data['Brand']['brand_type']="style";
					$this->data['Brand']['brand_description']=$this->data['Product']['sugeststyles'];
					$this->Brand->create();
					$this->Brand->save($this->data['Brand']);
					$style_id=$this->Brand->getlastinsertid();
					
					$this->data['Categorybrand']['brand_type']="style";
					$this->data['Categorybrand']['brand_id']=$style_id;
					$this->data['Categorybrand']['category_id']=$this->data['Product']['category_id'];					
					$this->Categorybrand->create();
					$this->Categorybrand->save($this->data['Categorybrand']);					
					$this->data['Product']['global_styles']=$style_id;
				}
				if(empty($this->data['Product']['global_conditions'])){
					$this->data['Product']['global_conditions']=0;
				}
				//if user suggested new condition
				if(isset($this->data['Product']['sugestconditions']) AND empty($this->data['Product']['global_conditions'])){
					$this->data['Brand']['brand_type']="condition";
					$this->data['Brand']['brand_description']=$this->data['Product']['sugestconditions'];
					$this->Brand->create();
					$this->Brand->save($this->data['Brand']);
					$condition_id=$this->Brand->getlastinsertid();
					
					$this->data['Categorybrand']['brand_type']="condition";
					$this->data['Categorybrand']['brand_id']=$condition_id;
					$this->data['Categorybrand']['category_id']=$this->data['Product']['category_id'];					
					$this->Categorybrand->create();
					$this->Categorybrand->save($this->data['Categorybrand']);					
					$this->data['Product']['global_conditions']=$condition_id;
				}
				$this->data['Product']['products_createDate']=date("Y-m-d H:s:i");
				$nextWeek = strtotime("+1 week");
				$this->data['Product']['products_expiredDate']=date("Y-m-d H:s:i",$nextWeek);
				
				if($this->Session->Check('Auth.User.group_id')==3){				
					$this->data['Product']['products_status']="Approved";
				}else{
					$this->data['Product']['products_status']="Pending";
				}
				
				$this->Product->create();
				if($this->Product->save($this->data)){
					$product_id=$this->Product->getlastinsertid();
					unset($data['fileName']);
					if(isset($data)){
						$i=1;
						foreach($data as $key=>$val){
							if(isset($val)){
								$this->data['ProductImage'][$i]['image']=$val['name'];
								$this->data['ProductImage'][$i]['product_id']=$product_id;						
								$this->data['ProductImage'][$i]['category_id']=$this->data['cat_id'];
								$i++;
							}
						}
						if(isset($this->data['ProductImage'])){
							$this->ProductImage->create();
							$this->ProductImage->saveAll($this->data['ProductImage']);
						}
					}
					//Additional Fields
					if(isset($this->data['AdditionalFieldValue'])){
						$i=0;
						foreach($this->data['AdditionalFieldValue'] as $tmp){
							if(isset($tmp['values'])){
								$this->data['ProductAdditionalFieldValue'][$i]['field_id']=$tmp['field_id'];
								if(isset($tmp['values'])){
									$options['fields']=array("Field.field_value");
									$options['conditions']=array("Field.id"=>$tmp['field_id']);
									$fields=$this->Field->find('first',$options);
									$dropdown_values=explode(",",$fields['Field']['field_value']);
									$this->data['ProductAdditionalFieldValue'][$i]['values']=$tmp['values'];
								}
							}
							if(isset($tmp['chk_values'])){
								$this->data['ProductAdditionalFieldValue'][$i]['field_id']=$tmp['field_id'];
								if(is_array($tmp['chk_values']))
									$this->data['ProductAdditionalFieldValue'][$i]['values']=implode(",",$tmp['chk_values']);
								else
									$this->data['ProductAdditionalFieldValue'][$i]['values']=$tmp['chk_values'];
							}
							$this->data['ProductAdditionalFieldValue'][$i]['product_id']=$product_id;
							if(isset($tmp['id'])){
								$this->data['ProductAdditionalFieldValue'][$i]['id']=$tmp['id'];
								}
							$i++;	
						}
						$this->ProductAdditionalFieldValue->create();
						$this->ProductAdditionalFieldValue->saveAll($this->data['ProductAdditionalFieldValue']);	
					}
					
					//Product sizes
					if(isset($this->data['ProductSize']) OR isset($this->data['ProductSizeLabel']) OR (isset($this->data['sizearray']) && isset($this->data['valuearray']))){
					$i=0;
					if(isset($this->data['ProductSize'])){
					foreach($this->data['ProductSize'] as $tmp){
						if(isset($tmp['sizevalue_id'])){
							$this->data['ProductSize'][$i]['product_id']=$product_id;
							$this->data['ProductSize'][$i]['category_id']=$this->data['Product']['category_id'];
							$this->data['ProductSize'][$i]['sizevalue_id']=$tmp['sizevalue_id'];				
							$this->data['ProductSize'][$i]['sizetitle_id']=$tmp['sizetitle_id'];				
							$this->data['ProductSize'][$i]['sizelabel_id']=0;				
							$i++;
						}
					}
					}
					
					if(isset($this->data['ProductSizeLabel'])){
					foreach($this->data['ProductSizeLabel'] as $tmp){
						if(isset($tmp['sizevalue_id'])){
							$this->data['ProductSize'][$i]['product_id']=$product_id;
							$this->data['ProductSize'][$i]['category_id']=$this->data['Product']['category_id'];
							$this->data['ProductSize'][$i]['sizevalue_id']=$tmp['sizevalue_id'];				
							$this->data['ProductSize'][$i]['sizetitle_id']=$tmp['sizetitle_id'];				
							$this->data['ProductSize'][$i]['sizelabel_id']=$tmp['sizelabel_id'];				
							$i++;
						}
					}
					}
					if(isset($this->data['sizearray']) && isset($this->data['valuearray'])){
						$this->data['ProductSize'][$i]['product_id']=$product_id;		
						$this->data['ProductSize'][$i]['category_id']=$this->data['Product']['category_id'];
						$this->data['ProductSize'][$i]['sizetitle_id']=$this->data['sizearray'];		
						$this->data['ProductSize'][$i]['sizevalue_id']=$this->data['valuearray'];		
						$this->data['ProductSize'][$i]['sizelabel_id']=0;				
					}
					
					$this->ProductSize->create();
					$this->ProductSize->saveAll($this->data['ProductSize']);
				}
					
					//Products Shipping Method 
					if(isset($this->data['ProductShippings'])){
					$i=0;					
					foreach($this->data['ProductShippings'] as $tmp){											
						$this->data['ProductShipping'][$i]['product_id']=$product_id;
						$this->data['ProductShipping'][$i]['shipping_id']=$tmp;							
						$i++;						
					}
					$this->ProductShipping->create();
					$this->ProductShipping->saveAll($this->data['ProductShipping']);
					}
					
					if((isset($this->data['Product']['product_international_shipping']) || $this->data['Product']['product_international_shipping']=='Yes') && isset($this->data['ProductInternationalShippings'])){
						//Products International Shipping Method						
						$i=0;					
						foreach($this->data['ProductInternationalShippings'] as $tmp){							
							if(isset($tmp['id']))
							$this->data['ProductInternationalShipping'][$i]['id']=$tmp['id'];							
							$this->data['ProductInternationalShipping'][$i]['shipping_id']=$tmp['shipping_id'];							
							$this->data['ProductInternationalShipping'][$i]['product_id']=$product_id;
														
							if($tmp['continent_id']=="custom_location"){
								$tmp['continent_id']=implode(",",$this->data['customlocation']);
							}
							
							$this->data['ProductInternationalShipping'][$i]['continent_id']=$tmp['continent_id'];							
							$this->data['ProductInternationalShipping'][$i]['shipping_cost']=$tmp['shipping_cost'];
							$i++;						
						}
						
						$this->ProductInternationalShipping->create();
						$this->ProductInternationalShipping->saveAll($this->data['ProductInternationalShipping']);
					}				
					if($this->Session->check('blockCountry')){
						$this->loadModel('Country');	
						$this->loadModel('Continent');	
						$this->loadModel('BlockCountryShip');
						$block_country = unserialize(base64_decode($this->Session->read('blockCountry')));
						if(!empty ($block_country['country_name'])){
						$totalcountry=$this->Country->find('count');
						for($i=0;$i<$totalcountry;$i++){
                                                if(isset ($block_country['country_name'][$i])){
						$str=explode('_', $block_country['country_name'][$i]);
							$country=$str[0];
							$con=$str[1];
							$cunt=$this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' =>$product_id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>$con,'BlockCountryShip.country_id' =>$country)));
							if($cunt<1){
								$this->data['BlockCountryShip']['id']=null;
								$this->data['BlockCountryShip']['seller_id']=$this->Auth->user('id');
								$this->data['BlockCountryShip']['country_id']=$country;
								$this->data['BlockCountryShip']['continent_id']=$con;
								$this->data['BlockCountryShip']['product_id']=$product_id;
							   $this->BlockCountryShip->save($this->data);
							}
						}else{

							$str=explode('_', $block_country['con_name'][$i]);
							$country=$str[0];
							$con=$str[1];
							$cunt=$this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' =>$product_id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>$con,'BlockCountryShip.country_id' =>$country)));
							
							if($cunt>0){
							   $con=array('BlockCountryShip.product_id' =>$product_id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>$con,'BlockCountryShip.country_id' =>$country);
							   $this->BlockCountryShip->deleteAll($con);
							}
						}											
						}
						$this->Session->setFlash(__('The Block countries has been Updated Successfully.', true));

						}else{
							 $totalcountry=$this->Country->find('count');
						for($i=0;$i<$totalcountry;$i++){
						  $str=explode('_', $block_country['con_name'][$i]);
							$country=$str[0];
							$con=$str[1];
							$cunt=$this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' =>$product_id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>$con,'BlockCountryShip.country_id' =>$country)));
							
							if($cunt>0){
								$con=array('BlockCountryShip.product_id' =>$product_id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>$con,'BlockCountryShip.country_id' =>$country);
							   $this->BlockCountryShip->deleteAll($con);
							}
						 }
						 $this->Session->setFlash(__('The Block countries has been Updated Successfully.', true));
						}
						$this->Session->delete('blockCountry');
					}				
					$this->Session->setFlash(__('The product has been saved', true));
					$this->redirect(array('action' => 'success'));
				}else{
					$this->Session->setFlash(__('The product could not be saved into database. Something went wrong please, try again.', true));
					$this->redirect(array('action' => 'success'));
				}						
            }
			}
		}	
		/***********************Domestic****************************/
		$this->Shipping->recursive=-1;
		$shippings=$this->Shipping->find("list");
		
		$this->loadModel('Continent');
		$this->Continent->recursive=-1;		
		$internationalocations=$this->Continent->find("list",array("fields"=>array("id","name"),"order"=>"name asc"));		
		
		$users = $this->Product->User->find('list');
		
		$categories = $this->Product->Category->find('list',array(
			'conditions'=>array('Category.parent_id'=>'0'),
			'order'=>'Category.category_order ASC'));
		$handalingtimes=$this->HandleTime->find('list');
		$this->set(compact('shippings', 'handalingtimes','users', 'categories','internationashippings','internationalocations','productinternationalshippings'));	
		$this->set('title_for_layout', 'Add Product');
		
		$this->set('item', $this->Category->categoryArray());
		$this->loadModel('Paymentmethod');
		$payments=$this->Paymentmethod->find("all");
		$this->data['payments']=$payments;		
	}
        
	function edit($id = null) {
		$this->layout="innerhome";
		///product chk by user
		$user_chk = $this->Product->find('count', array('conditions' => array('Product.user_id' =>$this->Auth->user('id'),'Product.id' =>$id)));
		$this->set('user_chk',$user_chk);
        if (!$id && empty($this->data)) {
			$this->set('user_chk','0');
		}                
		if (!empty($this->data)) {
			//$this->data = Sanitize::clean($this->data, array('remove_html' => true));
			
			if(empty($this->data['Product']['global_brands'])){
				$this->data['Product']['global_brands']=0;
			}
			if(isset($this->data['Product']['sugestbrands']) AND empty($this->data['Product']['global_brands'])){
				$this->data['Brand']['brand_type']="brand";
				$this->data['Brand']['brand_description']=$this->data['Product']['sugestbrands'];
				$this->Brand->create();
				$this->Brand->save($this->data['Brand']);
				$brand_id=$this->Brand->getlastinsertid();
				$this->data['Categorybrand']['brand_type']="brand";
				$this->data['Categorybrand']['brand_id']=$brand_id;
				$this->data['Categorybrand']['category_id']=$this->data['Product']['category_id'];
				$this->Categorybrand->create();
				$this->Categorybrand->save($this->data['Categorybrand']);
				$this->data['Product']['global_brands']=$brand_id;
			}
			
			if(empty($this->data['Product']['global_styles'])){
				$this->data['Product']['global_styles']=0;
			}
			//if user suggested new style
			if(isset($this->data['Product']['sugeststyles']) AND empty($this->data['Product']['global_styles'])){
				$this->data['Brand']['brand_type']="style";
				$this->data['Brand']['brand_description']=$this->data['Product']['sugeststyles'];
				$this->Brand->create();
				$this->Brand->save($this->data['Brand']);
				$style_id=$this->Brand->getlastinsertid();
				$this->data['Categorybrand']['brand_type']="style";
				$this->data['Categorybrand']['brand_id']=$style_id;
				$this->data['Categorybrand']['category_id']=$this->data['Product']['category_id'];					
				$this->Categorybrand->create();
				$this->Categorybrand->save($this->data['Categorybrand']);
				$this->data['Product']['global_styles']=$style_id;
			}
			if(empty($this->data['Product']['global_conditions'])){
				$this->data['Product']['global_conditions']=0;
			}
			//if user suggested new condition
				if(isset($this->data['Product']['sugestconditions']) AND empty($this->data['Product']['global_conditions'])){
					$this->data['Brand']['brand_type']="condition";
					$this->data['Brand']['brand_description']=$this->data['Product']['sugestconditions'];
					$this->Brand->create();
					$this->Brand->save($this->data['Brand']);
					$condition_id=$this->Brand->getlastinsertid();
					
					$this->data['Categorybrand']['brand_type']="condition";
					$this->data['Categorybrand']['brand_id']=$condition_id;
					$this->data['Categorybrand']['category_id']=$this->data['Product']['category_id'];					
					$this->Categorybrand->create();
					$this->Categorybrand->save($this->data['Categorybrand']);
					$this->data['Product']['global_conditions']=$condition_id;
				}
				$product_id=$this->data['Product']['id'];
				//uploading products image then add products
				if($image_data = $this->Uploader->uploadAll()){
					if(isset($image_data['fileName']['name']))
						$this->data['Product']['products_thumbnailImage']=$image_data['fileName']['name'];
					unset($image_data['fileName']);
					
					$cat_id=$this->data['Product']['category_id'];
					$i=1;
					if($this->data['ProductImage']){
					foreach($this->data['ProductImage'] as $key=>$val){
						if(isset($image_data['fileName'.$key])){
							$this->data['ProductImage']['image']=$image_data['fileName'.$key]['name'];
							if(isset($val['required'])){
								$this->data['ProductImage']['required']=$val['required'];
							}
							$this->data['ProductImage']['product_id']=$product_id;
							$this->data['ProductImage']['category_id']=$cat_id;
							if(isset($val['id'])){
								$this->data['ProductImage']['id']=$val['id'];
							}else{
								$this->ProductImage->create();
							}
							$this->ProductImage->save($this->data['ProductImage']);
						}
						$i++;
					}}
					
				}
				if(isset($this->data['AdditionalFieldValue'])){
					//Additional Fields 
					$i=0;
					foreach($this->data['AdditionalFieldValue'] as $tmp){
						if(isset($tmp['values'])){
							$this->data['ProductAdditionalFieldValue'][$i]['field_id']=$tmp['field_id'];
							
							if(isset($tmp['values'])){
								$options['fields']=array("Field.field_value");
								$options['conditions']=array("Field.id"=>$tmp['field_id']);
								$fields=$this->Field->find('first',$options);
								$dropdown_values=explode(",",$fields['Field']['field_value']);
								$this->data['ProductAdditionalFieldValue'][$i]['values']=$tmp['values'];
							}							
						}
						if(isset($tmp['chk_values'])){
							$this->data['ProductAdditionalFieldValue'][$i]['field_id']=$tmp['field_id'];
							if(is_array($tmp['chk_values']))
								$this->data['ProductAdditionalFieldValue'][$i]['values']=implode(",",$tmp['chk_values']);
							else
								$this->data['ProductAdditionalFieldValue'][$i]['values']=$tmp['chk_values'];
						}
						$this->data['ProductAdditionalFieldValue'][$i]['product_id']=$this->data['Product']['id'];
						if(isset($tmp['id'])){
							$this->data['ProductAdditionalFieldValue'][$i]['id']=$tmp['id'];
							}
						$i++;	
					}					
					$this->ProductAdditionalFieldValue->create();
					$this->ProductAdditionalFieldValue->saveAll($this->data['ProductAdditionalFieldValue']);	
				}	
				
				if($this->Session->Check('Auth.User.group_id')==3){
					$this->Session->setFlash(__('Product has been successfully updated and listed under product listing page.', 'flash_success'));
					$this->data['Product']['products_status']="Approved";
					}
				else{
					$this->Session->setFlash(__('This page will go to the Q admin if the following features change. If any from Block 2, block 3 (except gallery image), Block 4, the product page will go back to Q admin for approval.', 'flash_success'));
				
					if($this->data['Product']['productchange']==1)
					$this->data['Product']['products_status']="Pending";					
				}
			if ($this->Product->save($this->data)){
				if(isset($this->data['ProductSize']) OR isset($this->data['ProductSizeLabel']) OR (isset($this->data['sizearray']) && isset($this->data['valuearray']))){
					//Product sizes
					$i=0;	
					if(isset($this->data['ProductSize'])){
					foreach($this->data['ProductSize'] as $tmp){
						if(isset($tmp['sizevalue_id'])){
							$this->data['ProductSize'][$i]['product_id']=$this->data['Product']['id'];
							$this->data['ProductSize'][$i]['category_id']=$this->data['Product']['category_id'];
							$this->data['ProductSize'][$i]['sizevalue_id']=$tmp['sizevalue_id'];
							$this->data['ProductSize'][$i]['sizetitle_id']=$tmp['sizetitle_id'];
							$this->data['ProductSize'][$i]['sizelabel_id']=0;
							if(isset($tmp['id'])){
							$this->data['ProductSize'][$i]['id']=$tmp['id'];
							}
							$i++;
						}
					}
					}
					if(isset($this->data['ProductSizeLabel'])){
					foreach($this->data['ProductSizeLabel'] as $tmp){
						if(isset($tmp['sizevalue_id'])){
							$this->data['ProductSize'][$i]['product_id']=$product_id;
							$this->data['ProductSize'][$i]['category_id']=$this->data['Product']['category_id'];
							$this->data['ProductSize'][$i]['sizevalue_id']=$tmp['sizevalue_id'];
							$this->data['ProductSize'][$i]['sizetitle_id']=$tmp['sizetitle_id'];	
							$this->data['ProductSize'][$i]['sizelabel_id']=$tmp['sizelabel_id'];							
							if(isset($tmp['id'])){
							$this->data['ProductSize'][$i]['id']=$tmp['id'];							
							}
							$i++;
						}
					}
					}
					if(isset($this->data['sizearray']) && isset($this->data['valuearray'])){
						if(isset($this->data['productsizeid']))
						$this->data['ProductSize'][$i]['id']=$this->data['productsizeid'];		
						$this->data['ProductSize'][$i]['product_id']=$this->data['Product']['id'];		
						$this->data['ProductSize'][$i]['category_id']=$this->data['Product']['category_id'];
						$this->data['ProductSize'][$i]['sizetitle_id']=$this->data['sizearray'];		
						$this->data['ProductSize'][$i]['sizevalue_id']=$this->data['valuearray'];
						$this->data['ProductSize'][$i]['sizelabel_id']=0;						
					}
					$this->ProductSize->create();
					$this->ProductSize->saveAll($this->data['ProductSize']);
				}
				
				if(isset($this->data['ProductShippings'])){
					//Products Shipping Method 
					$i=0;
					foreach($this->data['ProductShippings'] as $tmp){
						$this->data['ProductShipping'][$i]['product_id']=$product_id;
						$this->data['ProductShipping'][$i]['shipping_id']=$tmp['shipping_id'];
						if(isset($tmp['id']))
						$this->data['ProductShipping'][$i]['id']=$tmp['id'];							
						$i++;
					}
					$this->ProductShipping->create();
					$this->ProductShipping->saveAll($this->data['ProductShipping']);
				}
				
				if((isset($this->data['Product']['product_international_shipping']) || $this->data['Product']['product_international_shipping']=='Yes') && isset($this->data['ProductInternationalShippings'])){
						//Products International Shipping Method
						$i=0;
						foreach($this->data['ProductInternationalShippings'] as $tmp){							
							if(isset($tmp['id']))
							$this->data['ProductInternationalShipping'][$i]['id']=$tmp['id'];							
							$this->data['ProductInternationalShipping'][$i]['shipping_id']=$tmp['shipping_id'];							
							$this->data['ProductInternationalShipping'][$i]['product_id']=$product_id;
							if($tmp['continent_id']=="custom_location"){
								$tmp['continent_id']=implode(",",$this->data['customlocation']);
							}
							$this->data['ProductInternationalShipping'][$i]['continent_id']=$tmp['continent_id'];							
							$this->data['ProductInternationalShipping'][$i]['shipping_cost']=$tmp['shipping_cost'];
							$i++;
						}
						$this->ProductInternationalShipping->create();
						$this->ProductInternationalShipping->saveAll($this->data['ProductInternationalShipping']);
					}
				
				if($this->Session->check('blockCountry')){
					$this->loadModel('Country');	
					$this->loadModel('Continent');	
					$this->loadModel('BlockCountryShip');
					$block_country = unserialize(base64_decode($this->Session->read('blockCountry')));
					if(!empty ($block_country['country_name'])){
						$totalcountry=$this->Country->find('count');
						for($i=0;$i<$totalcountry;$i++){

						if(isset ($block_country['country_name'][$i])){
						$str=explode('_', $block_country['country_name'][$i]);
							$country=$str[0];
							$con=$str[1];
							$cunt=$this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' =>$product_id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>$con,'BlockCountryShip.country_id' =>$country)));
							if($cunt<1){
								$this->data['BlockCountryShip']['id']=null;
								$this->data['BlockCountryShip']['seller_id']=$this->Auth->user('id');
								$this->data['BlockCountryShip']['country_id']=$country;
								$this->data['BlockCountryShip']['continent_id']=$con;
								$this->data['BlockCountryShip']['product_id']=$product_id;
							   $this->BlockCountryShip->save($this->data);
							}
						}else{

							$str=explode('_', $block_country['con_name'][$i]);
							$country=$str[0];
							$con=$str[1];
							$cunt=$this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' =>$product_id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>$con,'BlockCountryShip.country_id' =>$country)));
							
							if($cunt>0){
							   $con=array('BlockCountryShip.product_id' =>$product_id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>$con,'BlockCountryShip.country_id' =>$country);
							   $this->BlockCountryShip->deleteAll($con);
							}
						}
											
						}
						$this->Session->setFlash(__('The Block countries has been Updated Successfully.', true));

						}else{
							 $totalcountry=$this->Country->find('count');
						for($i=0;$i<$totalcountry;$i++){
						  $str=explode('_', $block_country['con_name'][$i]);
							$country=$str[0];
							$con=$str[1];
							$cunt=$this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' =>$product_id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>$con,'BlockCountryShip.country_id' =>$country)));
							
							if($cunt>0){
								$con=array('BlockCountryShip.product_id' =>$product_id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>$con,'BlockCountryShip.country_id' =>$country);
							   $this->BlockCountryShip->deleteAll($con);
							}
						}					 

						$this->Session->setFlash(__('The Block countries has been Updated Successfully.', true));
						}
						$this->Session->delete('blockCountry');
				}
				$this->redirect(array('action' => 'success'));
			} else {
				$this->Session->setFlash(__('The product could not be saved.  Something went wrong please, try again.', true));
				$this->redirect(array('action' => 'success'));
			}
		} 
		if (empty($this->data)) {
			$this->Product->recursive=0;
			$this->data = $this->Product->read(null,$id);
			if(!$this->data['Product']){
			$this->set('user_chk','0');
			}
			$this->data['ProductShippings']=$this->ProductShipping->find('all',array('conditions'=>array('ProductShipping.product_id'=>$id)));
			
			$this->ProductInternationalShipping->unbindModel(array('belongsTo' => array('Continent')));
			$productinternationalshippings= $this->ProductInternationalShipping->find('all',array('conditions'=>array('ProductInternationalShipping.product_id'=>$id)));
			$i=0;
			$this->loadModel("Continent");
			$this->Continent->recursive=-1;
			foreach($productinternationalshippings as $productinternationalshipping):
				if($productinternationalshipping['ProductInternationalShipping']['continent_id']!="worldwide"){
					$conID=explode(",",$productinternationalshipping['ProductInternationalShipping']['continent_id']);					
					$flag=1;
					$continent="";					
					foreach($conID as $continentID){
						$continent_name=$this->Continent->find("first",array("conditions"=>array("id"=>$continentID),"fields"=>array("name")));
						if($flag==1){
							$continent.=$continent_name['Continent']['name'];
							$flag=0;
						}	
						else	
							$continent.=", ".$continent_name['Continent']['name'];
					}
					$productinternationalshippings[$i]['ProductInternationalShipping']['continent_id']=$continent;					
				}
				else
					$productinternationalshippings[$i]['ProductInternationalShipping']['continent_id']=$productinternationalshipping['ProductInternationalShipping']['continent_id'];
				$i++;
			endforeach;
			$subcat=$this->chkHasParent($this->data['Product']['category_id']);
			$bredcrumb='<p><em>*</em> Current category: <span>';
			$this->Category->recursive=-1;
			if(isset($subcat['catid_label2'])){
				$catid_label2=$this->Category->findById($subcat['catid_label2']);
				$bredcrumb.=$catid_label2['Category']['category_name'];
			}
			if(isset($subcat['catid_label3'])){
				$catid_label3=$this->Category->findById($subcat['catid_label3']);
				$bredcrumb.=" >> ".$catid_label3['Category']['category_name'];
			}
			if(isset($subcat['catid_label4'])){
				$catid_label4=$this->Category->findById($subcat['catid_label4']);
				$bredcrumb.=" >> ".$catid_label4['Category']['category_name'];
			}
			if(isset($subcat['catid_label5'])){
				$catid_label5=$this->Category->findById($subcat['catid_label5']);
				$bredcrumb.=" >> ".$catid_label5['Category']['category_name'];
			}
			$bredcrumb.='</span></p>';
			$this->data['bredcrumb']=$bredcrumb;
			$this->data['subcat']=$subcat;
		}
		$users = $this->Product->User->find('list');
		$categories = $this->Product->Category->find('list',array(
			'conditions'=>array('Category.parent_id'=>'0'),
			'order'=>'Category.category_order ASC'));
		$this->Shipping->recursive=-1;		
		$shippings=$this->Shipping->find("list");		
		$handalingtimes=$this->HandleTime->find("list");
		$this->set(compact('shippings', 'handalingtimes'));
		$this->Country->recursive=-1;
		$this->loadModel("Continent");
		$internationalocations=$this->Continent->find("list",array("fields"=>array("id","name"),"order"=>"Continent.name asc"));		
		$this->set(compact('users','categories','internationalocations','productinternationalshippings'));
	}
	
	function sell_similar($id = null) {
		$this->layout="innerhome";
		///product chk by user
		$user_chk = $this->Product->find('count', array('conditions' => array('Product.user_id' =>$this->Auth->user('id'),'Product.id' =>$id)));
		$this->set('user_chk',$user_chk);
        if (!$id && empty($this->data)) {
			$this->set('user_chk','0');
		}
		if (!empty($this->data)) {
			//$this->data = Sanitize::clean($this->data, array('remove_html' => true));
			$this->Product->set($this->data);
			if ($this->Product->validates()){
					if(isset($this->data['Product']['sugestbrands']) && ($this->data['Product']['sugestbrands']=="Enter Brand")){
						$this->data['Product']['global_brands']=0;
					}
					//if user suggested new brand
					if(isset($this->data['Product']['sugestbrands']) && empty($this->data['Product']['global_brands'])){
						$this->data['Brand']['brand_type']="brand";
						$this->data['Brand']['brand_description']=$this->data['Product']['sugestbrands'];
						$this->Brand->create();
						$this->Brand->save($this->data['Brand']);
						$brand_id=$this->Brand->getlastinsertid();
						$this->data['Categorybrand']['brand_type']="brand";
						$this->data['Categorybrand']['brand_id']=$brand_id;
						$this->data['Categorybrand']['category_id']=$this->data['Product']['category_id'];					
						$this->Categorybrand->create();
						$this->Categorybrand->save($this->data['Categorybrand']);
						$this->data['Product']['global_brands']=$brand_id;
					}
					if(isset($this->data['Product']['sugeststyles']) && ($this->data['Product']['sugeststyles']=="Enter Style")){
						$this->data['Product']['global_styles']=0;
					}
					//if user suggested new style
					if(isset($this->data['Product']['sugeststyles']) && empty($this->data['Product']['global_styles'])){
						$this->data['Brand']['brand_type']="style";
						$this->data['Brand']['brand_description']=$this->data['Product']['sugeststyles'];
						$this->Brand->create();
						$this->Brand->save($this->data['Brand']);
						$style_id=$this->Brand->getlastinsertid();
						$this->data['Categorybrand']['brand_type']="style";
						$this->data['Categorybrand']['brand_id']=$style_id;
						$this->data['Categorybrand']['category_id']=$this->data['Product']['category_id'];					
						$this->Categorybrand->create();
						$this->Categorybrand->save($this->data['Categorybrand']);
						$this->data['Product']['global_styles']=$style_id;
					}
					if(isset($this->data['Product']['sugestconditions']) && ($this->data['Product']['sugestconditions']=="Enter Condition")){
						$this->data['Product']['global_conditions']=0;
					}
					//if user suggested new condition
					if(isset($this->data['Product']['sugestconditions']) && empty($this->data['Product']['global_conditions'])){
						$this->data['Brand']['brand_type']="condition";
						$this->data['Brand']['brand_description']=$this->data['Product']['sugestconditions'];
						$this->Brand->create();
						$this->Brand->save($this->data['Brand']);
						$condition_id=$this->Brand->getlastinsertid();
						$this->data['Categorybrand']['brand_type']="condition";
						$this->data['Categorybrand']['brand_id']=$condition_id;
						$this->data['Categorybrand']['category_id']=$this->data['Product']['category_id'];					
						$this->Categorybrand->create();
						$this->Categorybrand->save($this->data['Categorybrand']);					
						$this->data['Product']['global_conditions']=$condition_id;
					}
					$this->data['Product']['products_createDate']=date("Y-m-d H:s:i");
					$nextWeek = strtotime("+1 week");
					$this->data['Product']['products_expiredDate']=date("Y-m-d H:s:i",$nextWeek);
					if($image_data = $this->Uploader->uploadAll()){
						if(isset($image_data['fileName']['name']))
						$this->data['Product']['products_thumbnailImage']=$image_data['fileName']['name'];
					}
					$this->Product->create();
					if($this->Product->save($this->data)){
						$product_id=$this->Product->getlastinsertid();
							unset($image_data['fileName']);
							$cat_id=$this->data['cat_id'];
							$i=1;
							
							if($image_data){
								foreach($image_data as $key=>$val){
									if($val['name']){
										$this->data['ProductImage'][$i]['image']=$val['name'];
										$this->data['ProductImage'][$i]['product_id']=$product_id;
										$this->data['ProductImage'][$i]['category_id']=$cat_id;
										$i++;
									}
								}
								if(isset($this->data['ProductImage'])){
									$this->ProductImage->create();
									$this->ProductImage->saveAll($this->data['ProductImage']);
								}
							}
						
						//Additional Fields
						if(isset($this->data['AdditionalFieldValue'])){
							$i=0;
							foreach($this->data['AdditionalFieldValue'] as $tmp){
								if(isset($tmp['values'])){
									$this->data['ProductAdditionalFieldValue'][$i]['field_id']=$tmp['field_id'];
									
									if(isset($tmp['values'])){
										$options['fields']=array("Field.field_value");
										$options['conditions']=array("Field.id"=>$tmp['field_id']);
										$fields=$this->Field->find('first',$options);
										$dropdown_values=explode(",",$fields['Field']['field_value']);
										$this->data['ProductAdditionalFieldValue'][$i]['values']=$tmp['values'];
									}							
								}
								if(isset($tmp['chk_values'])){
									$this->data['ProductAdditionalFieldValue'][$i]['field_id']=$tmp['field_id'];
									if(is_array($tmp['chk_values']))
										$this->data['ProductAdditionalFieldValue'][$i]['values']=implode(",",$tmp['chk_values']);
									else
										$this->data['ProductAdditionalFieldValue'][$i]['values']=$tmp['chk_values'];
								}
								$this->data['ProductAdditionalFieldValue'][$i]['product_id']=$product_id;
								$i++;
							}
							$this->ProductAdditionalFieldValue->create();
							$this->ProductAdditionalFieldValue->saveAll($this->data['ProductAdditionalFieldValue']);	
						}
					//Product sizes
					if(isset($this->data['ProductSize']) OR isset($this->data['ProductSizeLabel']) OR (isset($this->data['sizearray']) && isset($this->data['valuearray']))){
					//Product sizes
					$i=0;	
					if(isset($this->data['ProductSize'])){
					foreach($this->data['ProductSize'] as $tmp){
						if(isset($tmp['sizevalue_id'])){
							$this->data['ProductSize'][$i]['product_id']=$this->data['Product']['id'];
							$this->data['ProductSize'][$i]['category_id']=$this->data['Product']['category_id'];
							$this->data['ProductSize'][$i]['sizevalue_id']=$tmp['sizevalue_id'];
							$this->data['ProductSize'][$i]['sizetitle_id']=$tmp['sizetitle_id'];
							$this->data['ProductSize'][$i]['sizelabel_id']=0;
							if(isset($tmp['id'])){
							$this->data['ProductSize'][$i]['id']=$tmp['id'];
							}
							$i++;
						}
					}
					}
					if(isset($this->data['ProductSizeLabel'])){
					foreach($this->data['ProductSizeLabel'] as $tmp){
						if(isset($tmp['sizevalue_id'])){
							$this->data['ProductSize'][$i]['product_id']=$product_id;
							$this->data['ProductSize'][$i]['category_id']=$this->data['Product']['category_id'];
							$this->data['ProductSize'][$i]['sizevalue_id']=$tmp['sizevalue_id'];
							$this->data['ProductSize'][$i]['sizetitle_id']=$tmp['sizetitle_id'];	
							$this->data['ProductSize'][$i]['sizelabel_id']=$tmp['sizelabel_id'];							
							if(isset($tmp['id'])){
							$this->data['ProductSize'][$i]['id']=$tmp['id'];							
							}
							$i++;
						}
					}
					}
					if(isset($this->data['sizearray']) && isset($this->data['valuearray'])){
						if(isset($this->data['productsizeid']))
						$this->data['ProductSize'][$i]['id']=$this->data['productsizeid'];		
						$this->data['ProductSize'][$i]['product_id']=$this->data['Product']['id'];		
						$this->data['ProductSize'][$i]['category_id']=$this->data['Product']['category_id'];
						$this->data['ProductSize'][$i]['sizetitle_id']=$this->data['sizearray'];		
						$this->data['ProductSize'][$i]['sizevalue_id']=$this->data['valuearray'];
						$this->data['ProductSize'][$i]['sizelabel_id']=0;						
					}
					$this->ProductSize->create();
					$this->ProductSize->saveAll($this->data['ProductSize']);
				}
						//Products Shipping Method 
						$this->ProductShipping->recursive=-1;
						$domestic_shippings=$this->ProductShipping->find("all",array("conditions"=>array("ProductShipping.product_id"=>$this->data['Product']['pid'])));
						$i=0;
						if($domestic_shippings){
							foreach($domestic_shippings as $domestic_shipping){
								$this->data['ProductShippings'][$i]['product_id']=$product_id;
								$this->data['ProductShippings'][$i]['shipping_id']=$domestic_shipping['ProductShipping']['shipping_id'];
								$i++;
							}
						}
						if(isset($this->data['ProductShippings'])){							
							foreach($this->data['ProductShippings'] as $tmp){
								$this->data['ProductShipping'][$i]['product_id']=$product_id;
								$this->data['ProductShipping'][$i]['shipping_id']=$tmp['shipping_id'];
								$i++;
							}
							$this->ProductShipping->create();
							$this->ProductShipping->saveAll($this->data['ProductShipping']);
						}
															
						$this->ProductInternationalShipping->recursive=-1;
						$international_shippings=$this->ProductInternationalShipping->find("all",array("conditions"=>array("ProductInternationalShipping.product_id"=>$this->data['Product']['pid'])));
						$i=0;
						if($international_shippings){
							foreach($international_shippings as $international_shipping){
								$this->data['ProductInternationalShippings'][$i]['shipping_id']=$international_shipping['ProductInternationalShipping']['shipping_id'];							
								$this->data['ProductInternationalShippings'][$i]['product_id']=$product_id;
								$this->data['ProductInternationalShippings'][$i]['continent_id']=$international_shipping['ProductInternationalShipping']['continent_id'];
								$this->data['ProductInternationalShippings'][$i]['shipping_cost']=$international_shipping['ProductInternationalShipping']['shipping_cost'];
								$i++;
							}
						}
						if((isset($this->data['Product']['product_international_shipping']) || $this->data['Product']['product_international_shipping']=='Yes') && isset($this->data['ProductInternationalShippings'])){
							foreach($this->data['ProductInternationalShippings'] as $tmp){
								$this->data['ProductInternationalShipping'][$i]['shipping_id']=$tmp['shipping_id'];							
								$this->data['ProductInternationalShipping'][$i]['product_id']=$product_id;
								if($tmp['continent_id']=="custom_location"){
									$tmp['continent_id']=implode(",",$this->data['customlocation']);
								}
								$this->data['ProductInternationalShipping'][$i]['continent_id']=$tmp['continent_id'];
								$this->data['ProductInternationalShipping'][$i]['shipping_cost']=$tmp['shipping_cost'];
								$i++;
							}
							$this->ProductInternationalShipping->create();
							$this->ProductInternationalShipping->saveAll($this->data['ProductInternationalShipping']);
						}
						if($this->Session->check('blockCountry')){
							$this->loadModel('Country');	
							$this->loadModel('Continent');	
							$this->loadModel('BlockCountryShip');
							$block_country = unserialize(base64_decode($this->Session->read('blockCountry')));
							if(!empty ($block_country['country_name'])){
								$totalcountry=$this->Country->find('count');
								for($i=0;$i<$totalcountry;$i++){
									if(isset ($block_country['country_name'][$i])){
										$str=explode('_', $block_country['country_name'][$i]);
										$country=$str[0];
										$con=$str[1];
										$cunt=$this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' =>$product_id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>$con,'BlockCountryShip.country_id' =>$country)));
										if($cunt<1){
											$this->data['BlockCountryShip']['id']=null;
											$this->data['BlockCountryShip']['seller_id']=$this->Auth->user('id');
											$this->data['BlockCountryShip']['country_id']=$country;
											$this->data['BlockCountryShip']['continent_id']=$con;
											$this->data['BlockCountryShip']['product_id']=$product_id;
											$this->BlockCountryShip->save($this->data);
										}
									}else{
										$str=explode('_', $block_country['con_name'][$i]);
										$country=$str[0];
										$con=$str[1];
										$cunt=$this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' =>$product_id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>$con,'BlockCountryShip.country_id' =>$country)));
										if($cunt>0){
											$con=array('BlockCountryShip.product_id' =>$product_id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>$con,'BlockCountryShip.country_id' =>$country);
											$this->BlockCountryShip->deleteAll($con);
										}
									}
								}
								$this->Session->setFlash(__('The Block countries has been Updated Successfully.', true));
							}else{
								$totalcountry=$this->Country->find('count');
								for($i=0;$i<$totalcountry;$i++){
									$str=explode('_', $block_country['con_name'][$i]);
									$country=$str[0];
									$con=$str[1];
									$cunt=$this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' =>$product_id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>$con,'BlockCountryShip.country_id' =>$country)));
									if($cunt>0){
										$con=array('BlockCountryShip.product_id' =>$product_id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>$con,'BlockCountryShip.country_id' =>$country);
										$this->BlockCountryShip->deleteAll($con);
									}
								}
								$this->Session->setFlash(__('The Block countries has been Updated Successfully.', true));
							}
							$this->Session->delete('blockCountry');
						}
						$this->Session->setFlash(__('The product has been saved', true));
						$this->redirect(array('action' => 'success'));
					}else{
						$this->Session->setFlash(__('The product could not be saved. Something went wrong please, try again.', true));
						$this->redirect(array('action' => 'success'));
					}
			}
		}
		if (empty($this->data)) {
			$this->Product->recursive=0;
			$this->data = $this->Product->read(null,$id);
			if(!$this->data['Product']){
			$this->Session->setFlash(__('Invalid product ID', true));
			$this->redirect(array('action' => 'success'));
			}
			$this->data['ProductShippings']=$this->ProductShipping->find('all',array('conditions'=>array('ProductShipping.product_id'=>$id)));
			$this->ProductInternationalShipping->unbindModel(array('belongsTo' => array('Continent')));
			$productinternationalshippings= $this->ProductInternationalShipping->find('all',array('conditions'=>array('ProductInternationalShipping.product_id'=>$id)));
			$i=0;
			$this->loadModel("Continent");
			$this->Continent->recursive=-1;
			foreach($productinternationalshippings as $productinternationalshipping):
				if($productinternationalshipping['ProductInternationalShipping']['continent_id']!="worldwide"){
					$conID=explode(",",$productinternationalshipping['ProductInternationalShipping']['continent_id']);					
					$flag=1;
					$continent="";					
					foreach($conID as $continentID){
						$continent_name=$this->Continent->find("first",array("conditions"=>array("id"=>$continentID),"fields"=>array("name")));
						if($flag==1){
							$continent.=$continent_name['Continent']['name'];
							$flag=0;
						}	
						else	
							$continent.=", ".$continent_name['Continent']['name'];
					}
					$productinternationalshippings[$i]['ProductInternationalShipping']['continent_id']=$continent;					
				}
				else
					$productinternationalshippings[$i]['ProductInternationalShipping']['continent_id']=$productinternationalshipping['ProductInternationalShipping']['continent_id'];
				$i++;
			endforeach;
			
			$subcat=$this->chkHasParent($this->data['Product']['category_id']);
			$bredcrumb='<p><em>*</em> Current category: <span>';
			$this->Category->recursive=-1;
			if(isset($subcat['catid_label2'])){
				$catid_label2=$this->Category->findById($subcat['catid_label2']);
				$bredcrumb.=$catid_label2['Category']['category_name'];
			}
			if(isset($subcat['catid_label3'])){
				$catid_label3=$this->Category->findById($subcat['catid_label3']);
				$bredcrumb.=" >> ".$catid_label3['Category']['category_name'];
			}
			if(isset($subcat['catid_label4'])){
				$catid_label4=$this->Category->findById($subcat['catid_label4']);
				$bredcrumb.=" >> ".$catid_label4['Category']['category_name'];
			}
			if(isset($subcat['catid_label5'])){
				$catid_label5=$this->Category->findById($subcat['catid_label5']);
				$bredcrumb.=" >> ".$catid_label5['Category']['category_name'];
			}
			$bredcrumb.='</span></p>';
			$this->data['bredcrumb']=$bredcrumb;
			$this->data['subcat']=$subcat;
		}
		$users = $this->Product->User->find('list');
		$categories = $this->Product->Category->find('list',array(
			'conditions'=>array('Category.parent_id'=>'0'),
			'order'=>'Category.category_order ASC'));
		$this->Shipping->recursive=-1;
		$shippings=$this->Shipping->find("list");
		$handalingtimes=$this->HandleTime->find("list");
		$this->set(compact('shippings', 'handalingtimes'));	
		$this->Country->recursive=-1;
		$this->loadModel("Continent");
		$internationalocations=$this->Continent->find("list",array("fields"=>array("id","name"),"order"=>"Continent.name asc"));		
		$this->set(compact('users', 'categories','internationashippings','internationalocations','productinternationalshippings'));
	}
	
	function international_cost($id=null){
		$this->layout=false;		
		$this->loadModel("ProductInternationalShipping");
		$international_cost=$this->ProductInternationalShipping->find("all");		
		echo json_encode($international_cost);
		$this->autoRender=false;
	}
        
    function unsold() {
		$this->Product->recursive = -1;        
		$this->paginate = array('limit' => 25,'conditions'=>array('Product.user_id'=>$this->Auth->User('id'),'Product.products_status'=>'Unsold'),'order' => array('Product.id' => 'desc'));
		$this->set('products', $this->paginate());
		$this->layout="innerhome";
	}

        function pending() {
		$this->Product->recursive = -1;
		$this->paginate = array('limit' => 25,'conditions'=>array('Product.user_id'=>$this->Auth->User('id'),'Product.products_status'=>'Pending'),'order' => array('Product.id' => 'desc'));
		$this->set('products', $this->paginate());
		$this->layout="innerhome";
	}

      function disapproved() {
		$this->Product->recursive = -1;
		$this->paginate = array('limit' => 25,'conditions'=>array('Product.user_id'=>$this->Auth->User('id'),'Product.products_status'=>'Disapproved'),'order' => array('Product.id' => 'desc'));
		$this->set('products', $this->paginate());
		$this->layout="innerhome";
	}

function backstage_ptrack_approved($serchkey=null, $type=null) {
        $this->Product->recursive = 1;
        $this->Product->Behaviors->attach('Containable');
        /* if($this->Session->read('grouptype')!='S-Admins'){

          $this->loadModel('BrandPermission');

          $bids=$this->BrandPermission->findAllByUserId($this->Auth->User('id'),array('brand_id'));

          if(!empty($bids)){
          foreach($bids as $bid){
          $brandids[]=$bid['BrandPermission']['brand_id'];
          }

          $this->Product->contain('User.username');

          if(!empty($_POST['serchkey'])){
          $type=$this->data['type'];
          $serchkey=$_POST['serchkey'];
          $this->set('type',$type);
          $this->set('serchkey',$serchkey);
          }else{
          $this->set('type',$type);
          $this->set('serchkey',$serchkey);
          }

          if($serchkey!=null){
          if ($type == 'item') {
          /////////////////////////

          $this->paginate = array('limit' => 25,
          'conditions'=>array('OR'=>array('Product.global_brands'=> $brandids,
          'Product.global_styles'=> $brandids,
          'Product.global_conditions'=> $brandids),
          'OR'=>array(array('Product.products_status' => 'Approved'),array('Product.products_status' => 'Active')),
          'Product.id'=> $serchkey),
          'order' => array('Product.id' => 'desc'),
          'fields'=>array('Product.id','Product.products_thumbnailImage','Product.products_title','Product.user_id','Product.approved_id','Product.approved_date','Product.products_status'),
          'contain'=>array(
          'User.username',
          'Approver.username'
          )
          );
          //////////////////////
          }
          if ($type == 'title') {
          /////////////////////////
          $this->paginate = array('limit' => 25,
          'conditions'=>array('OR'=>array('Product.global_brands'=> $brandids,
          'Product.global_styles'=> $brandids,
          'Product.global_conditions'=> $brandids),
          'OR'=>array(array('Product.products_status' => 'Approved'),array('Product.products_status' => 'Active')),
          'Product.products_title like' => '%' .$serchkey.'%'),
          'order' => array('Product.id' => 'desc'),
          'fields'=>array('Product.id','Product.products_thumbnailImage','Product.products_title','Product.user_id','Product.approved_id','Product.approved_date','Product.products_status'),
          'contain'=>array(
          'User.username',
          'Approver.username'
          )
          );
          //////////////////////
          }
          if ($type == 'sellerid') {
          /////////////////////////

          $this->paginate = array('limit' => 25,
          'conditions'=>array('OR'=>array('Product.global_brands'=> $brandids,
          'Product.global_styles'=> $brandids,
          'Product.global_conditions'=> $brandids),
          'OR'=>array(array('Product.products_status' => 'Approved'),array('Product.products_status' => 'Active')),
          'User.username'=> $serchkey),
          'order' => array('Product.id' => 'desc'),
          'fields'=>array('Product.id','Product.products_thumbnailImage','Product.products_title','Product.user_id','Product.approved_id','Product.approved_date','Product.products_status'),
          'contain'=>array(
          'User.username',
          'Approver.username'
          )
          );
          //////////////////////
          }
          }else{
          $this->paginate = array('limit' => 25,
          'conditions'=>array('OR'=>array('Product.global_brands'=> $brandids,
          'Product.global_styles'=> $brandids,
          'Product.global_conditions'=> $brandids),
          'OR'=>array(array('Product.products_status' => 'Approved'),array('Product.products_status' => 'Active')),
          'order' => array('Product.id' => 'desc'),
          'fields'=>array('Product.id','Product.products_thumbnailImage','Product.products_title','Product.user_id','Product.approved_id','Product.approved_date','Product.products_status'),
          'contain'=>array(
          'User.username',
          'Approver.username'
          )
          );
          }
          $this->set('products', $this->paginate());
          }else{
          $this->set('products', '');
          }

          }else{ */
        //////////For Super Admin/////
    $this->Product->contain('User.username');
    if (!empty($_POST['serchkey'])) {
            $type = $this->data['type'];
            $serchkey = $_POST['serchkey'];
            $this->set('type', $type);
            $this->set('serchkey', $serchkey);
        } else {
            $this->set('type', $type);
            $this->set('serchkey', $serchkey);
        }
        if ($serchkey != null) {
            if ($type == 'item') {
                $this->paginate = array('limit' => 25,
                    'conditions' => array(
                        'OR'=>array(array('Product.products_status' => 'Approved'),array('Product.products_status' => 'Active')),
                        'Product.id' => $serchkey),
                    'order' => array('Product.id' => 'desc'),
                    'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.approved_date', 'Product.products_status'),
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }
            if ($type == 'title') {
                $this->paginate = array('limit' => 25,
                    'conditions' => array(
                        'OR'=>array(array('Product.products_status' => 'Approved'),array('Product.products_status' => 'Active')),
                        'Product.products_title like' => '%' . $serchkey . '%'),
                    'order' => array('Product.id' => 'desc'),
                    'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.approved_date', 'Product.products_status'),
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }
            if ($type == 'sellerid') {
                $this->paginate = array('limit' => 25,
                    'conditions' => array(
                        'OR'=>array(array('Product.products_status' => 'Approved'),array('Product.products_status' => 'Active')),
                        'User.username' => $serchkey),
                    'order' => array('Product.id' => 'desc'),
                    'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.approved_date', 'Product.products_status'),
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }
        } else {
            $this->paginate = array('limit' => 25,
                'conditions' => array(
                    'OR'=>array(array('Product.products_status' => 'Approved'),array('Product.products_status' => 'Active')),),
                'order' => array('Product.id' => 'desc'),
                'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.approved_date', 'Product.products_status'),
                'contain' => array(
                    'User.username',
                    'Approver.username'
                )
            );
        }
       $this->set('products', $this->paginate());
       $this->layout = "admin";
    }

 function backstage_ptrack_pending($serchkey=null, $type=null) {
        $this->Product->recursive = 1;
        $this->Product->Behaviors->attach('Containable');
       /* if ($this->Session->read('grouptype') != 'S-Admins') {
            $this->loadModel('BrandPermission');
            $bids = $this->BrandPermission->findAllByUserId($this->Auth->User('id'), array('brand_id'));
            if (!empty($bids)) {
                foreach ($bids as $bid) {
                    $brandids[] = $bid['BrandPermission']['brand_id'];
                }
              $this->Product->contain('User.username');
                if (!empty($_POST['serchkey'])) {
                    $type = $this->data['type'];
                    $serchkey = $_POST['serchkey'];
                    $this->set('type', $type);
                    $this->set('serchkey', $serchkey);
                } else {
                    $this->set('type', $type);
                    $this->set('serchkey', $serchkey);
                }
        if ($serchkey != null) {
                    if ($type == 'item') {
                        $this->paginate = array('limit' => 25,
                            'conditions' => array('OR' => array('Product.global_brands' => $brandids,
                                    'Product.global_styles' => $brandids,
                                    'Product.global_conditions' => $brandids),
                                'Product.products_status' => 'Pending',
                                'Product.id' => $serchkey),
                            'order' => array('Product.id' => 'desc'),
                            'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.products_createDate', 'Product.products_status'),
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    }
                    if ($type == 'title') {
                        $this->paginate = array('limit' => 25,
                            'conditions' => array('OR' => array('Product.global_brands' => $brandids,
                                    'Product.global_styles' => $brandids,
                                    'Product.global_conditions' => $brandids),
                                'Product.products_status' => 'Pending',
                                'Product.products_title like' => '%' . $serchkey . '%'),
                            'order' => array('Product.id' => 'desc'),
                            'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.products_createDate', 'Product.products_status'),
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    }
                    if ($type == 'sellerid') {
                        $this->paginate = array('limit' => 25,
                            'conditions' => array('OR' => array('Product.global_brands' => $brandids,
                                    'Product.global_styles' => $brandids,
                                    'Product.global_conditions' => $brandids),
                                'Product.products_status' => 'Pending',
                                'User.username' => $serchkey),
                            'order' => array('Product.id' => 'desc'),
                            'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.products_createDate', 'Product.products_status'),
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    }
                } else {
                    $this->paginate = array('limit' => 25,
                        'conditions' => array('OR' => array('Product.global_brands' => $brandids,
                                'Product.global_styles' => $brandids,
                                'Product.global_conditions' => $brandids),
                            'Product.products_status' => 'Pending'),
                        'order' => array('Product.id' => 'desc'),
                        'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.products_createDate', 'Product.products_status'),
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                }
                $this->set('products', $this->paginate());
            } else {
                $this->set('products', '');
            }
        } else {*/
            /////////for super admin//////////
            $this->Product->contain('User.username');
            if (!empty($_POST['serchkey'])) {
                $type = $this->data['type'];
                $serchkey = $_POST['serchkey'];
                $this->set('type', $type);
                $this->set('serchkey', $serchkey);
            } else {
                $this->set('type', $type);
                $this->set('serchkey', $serchkey);
            }
        if ($serchkey != null) {
                if ($type == 'item') {
                    $this->paginate = array('limit' => 25,
                        'conditions' => array(
                            'Product.products_status' => 'Pending',
                            'Product.id' => $serchkey),
                        'order' => array('Product.id' => 'desc'),
                        'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.products_createDate', 'Product.products_status'),
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                }
                if ($type == 'title') {
                    $this->paginate = array('limit' => 25,
                        'conditions' => array(
                            'Product.products_status' => 'Pending',
                            'Product.products_title like' => '%' . $serchkey . '%'),
                        'order' => array('Product.id' => 'desc'),
                        'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.products_createDate', 'Product.products_status'),
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                }
                if ($type == 'sellerid') {
                    $this->paginate = array('limit' => 25,
                        'conditions' => array(
                            'Product.products_status' => 'Pending',
                            'User.username' => $serchkey),
                        'order' => array('Product.id' => 'desc'),
                        'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.products_createDate', 'Product.products_status'),
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                }
            } else {
                $this->paginate = array('limit' => 25,
                    'conditions' => array(
                        'Product.products_status' => 'Pending'),
                    'order' => array('Product.id' => 'desc'),
                    'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.products_createDate', 'Product.products_status'),
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }
            $this->set('products', $this->paginate());
        //}
        $this->layout = "admin";
    }

     function backstage_ptrack_disapproved($serchkey=null, $type=null) {
        $this->Product->recursive = 1;
        $this->Product->Behaviors->attach('Containable');
       /* if ($this->Session->read('grouptype') != 'S-Admins') {
            $this->loadModel('BrandPermission');
            $bids = $this->BrandPermission->findAllByUserId($this->Auth->User('id'), array('brand_id'));
       if (!empty($bids)) {
                foreach ($bids as $bid) {
                    $brandids[] = $bid['BrandPermission']['brand_id'];
                }
                $this->Product->contain('User.username');
                if (!empty($_POST['serchkey'])) {
                    $type = $this->data['type'];
                    $serchkey = $_POST['serchkey'];
                    $this->set('type', $type);
                    $this->set('serchkey', $serchkey);
                } else {
                    $this->set('type', $type);
                    $this->set('serchkey', $serchkey);
                }
                if ($serchkey != null) {
                    if ($type == 'item') {
                        $this->paginate = array('limit' => 25,
                            'conditions' => array('OR' => array('Product.global_brands' => $brandids,
                                    'Product.global_styles' => $brandids,
                                    'Product.global_conditions' => $brandids),
                                'Product.products_status' => 'Disapproved',
                                'Product.id' => $serchkey),
                            'order' => array('Product.id' => 'desc'),
                            'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.disapproved_date', 'Product.products_status'),
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    }
                    if ($type == 'title') {
                        $this->paginate = array('limit' => 25,
                            'conditions' => array('OR' => array('Product.global_brands' => $brandids,
                                    'Product.global_styles' => $brandids,
                                    'Product.global_conditions' => $brandids),
                                'Product.products_status' => 'Disapproved',
                                'Product.products_title like' => '%' . $serchkey . '%'),
                            'order' => array('Product.id' => 'desc'),
                            'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.disapproved_date', 'Product.products_status'),
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    }
                    if ($type == 'sellerid') {
                        $this->paginate = array('limit' => 25,
                            'conditions' => array('OR' => array('Product.global_brands' => $brandids,
                                    'Product.global_styles' => $brandids,
                                    'Product.global_conditions' => $brandids),
                                'Product.products_status' => 'Disapproved',
                                'User.username' => $serchkey),
                            'order' => array('Product.id' => 'desc'),
                            'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.disapproved_date', 'Product.products_status'),
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    }
                } else {
                    $this->paginate = array('limit' => 25,
                        'conditions' => array('OR' => array('Product.global_brands' => $brandids,
                                'Product.global_styles' => $brandids,
                                'Product.global_conditions' => $brandids),
                            'Product.products_status' => 'Disapproved'),
                        'order' => array('Product.id' => 'desc'),
                        'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.disapproved_date', 'Product.products_status'),
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                }
                $this->set('products', $this->paginate());
            } else {
                $this->set('products', '');
            }
        } else {*/
            $this->Product->contain('User.username');
            if (!empty($_POST['serchkey'])) {
                $type = $this->data['type'];
                $serchkey = $_POST['serchkey'];
                $this->set('type', $type);
                $this->set('serchkey', $serchkey);
            } else {
                $this->set('type', $type);
                $this->set('serchkey', $serchkey);
            }
            if ($serchkey != null) {
                if ($type == 'item') {
                    $this->paginate = array('limit' => 25,
                        'conditions' => array(
                            'Product.products_status' => 'Disapproved',
                            'Product.id' => $serchkey),
                        'order' => array('Product.id' => 'desc'),
                        'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.disapproved_date', 'Product.products_status'),
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                }
                if ($type == 'title') {
                    $this->paginate = array('limit' => 25,
                        'conditions' => array(
                            'Product.products_status' => 'Disapproved',
                            'Product.products_title like' => '%' . $serchkey . '%'),
                        'order' => array('Product.id' => 'desc'),
                        'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.disapproved_date', 'Product.products_status'),
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                }
                if ($type == 'sellerid') {
                    $this->paginate = array('limit' => 25,
                        'conditions' => array(
                            'Product.products_status' => 'Disapproved',
                            'User.username' => $serchkey),
                        'order' => array('Product.id' => 'desc'),
                        'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.disapproved_date', 'Product.products_status'),
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                }
            } else {
                $this->paginate = array('limit' => 25,
                    'conditions' => array(
                        'Product.products_status' => 'Disapproved'),
                    'order' => array('Product.id' => 'desc'),
                    'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.approved_id', 'Product.disapproved_date', 'Product.products_status'),
                    'contain' => array(
                        'User.username',
                        'Approver.username'
                    )
                );
            }
            $this->set('products', $this->paginate());
        ///}
        $this->layout = "admin";
    }

    function view_comment($id = null) {
               $this->Product->Behaviors->attach('Containable');
               $this->Product->contain('User.username','Approver.username');
        	$this->set('product', $this->Product->read(array('Product.id','Product.disapprove_comments'), $id));
		$this->layout=false;
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid product', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('product', $this->Product->read(null, $id));
		$this->layout="innerhome";
	}
	//fetch images
	function fetchimages($id=null,$id2=null){
		$this->layout=false;		
		if(!$id2){
			$this->Imagetitle->recursive = -1;
			$imagetitles = $this->Imagetitle->find('all',array(
				'conditions'=>array('Imagetitle.category_id'=>$id),
				'order'=>'Imagetitle.id ASC'));									
		}
		else{			
			$conditions=array('ProductImage.product_id'=>$id2,'ProductImage.category_id'=>$id);			
			$imagetitles=$this->ProductImage->find("all",array('conditions'=>$conditions));				
			if(count($imagetitles)<1){
				$imagetitles = $this->Imagetitle->find('all',array(
				'conditions'=>array('Imagetitle.category_id'=>$id),
				'order'=>'Imagetitle.id ASC'));
				}
			}
			$this->data['cat_id']=$id;
			$this->set(compact('imagetitles'));
	}
	
	//fetch sub category
	function fetchSubCategory($id=null,$id2=null){
		$this->layout=false;
		$categories = $this->Category->fetchSubCategory($id);
		$this->set(compact('categories'));		
		$this->data['cat_id']=$id;		
		$this->data['selected_id']=$id2;		
	}

        function fetchParentCategory($id=null){
		$this->layout=false;
		$categories = $this->Category->fetchParentCategory($id);
		$this->set(compact('categories'));
		if($id)
		$this->data['cat_id']=$id;
	}
	
	function fetchbrand($id=null,$id2=null){
		$this->layout=false;
		$categorybrands=$this->Categorybrand->fetchbrand($id,$id2);
		$this->set(compact('categorybrands'));		
		$this->data['sel_id']=$id2;
	}
	function fetchstyle($id=null,$id2=null){
		$this->layout=false;
		$categorybrands=$this->Categorybrand->fetchstyle($id,$id2);
		$this->set(compact('categorybrands'));			
		$this->data['sel_id']=$id2;		
	}
	function fetchcondition($id=null,$id2=null){
		$this->layout=false;
		$categorybrands=$this->Categorybrand->fetchcondition($id,$id2);
		$this->set(compact('categorybrands'));		
		$this->data['sel_id']=$id2;		
	}
	
	function findParentsId($id=null){
		$this->layout=false;
		return $this->Category->findParentsId($id);
	}
	
	function checkHasFields($id=null,$id2=null,$pid=null){
		$this->layout=false;
		$this->Field->recursive = -1;
		$cat_id=$id;
		$options['order']=array('Field.id' => 'asc');
		$options['conditions']=array('Field.category_id'=>$cat_id);
		if($this->Field->find('count',$options)>0){
			$this->loadModel("Label");
			$labels=$this->Field->Label->find('all',array("conditions"=>array("Label.category_id"=>$cat_id),"order"=>"Label.id ASC"));
			$i=0;
			foreach($labels as $label){
				$options['conditions']=array('Field.category_id'=>$cat_id,'Field.label_id'=>$label['Label']['id']);
				$labels[$i]['hasfield']=$this->Field->find('count',$options);				
				$i++;
			}
			
			$this->set(compact('labels','cat_id','pid'));
			return true;
		}else
			return false;
	}
	
	function fetchadditionalfields_details_label($id=null,$id2=null){
		$this->layout=false;
		if(!$this->checkHasFields($id,"",$id2)){
			$parentId=$this->findParentsId($id);
			if(!$this->checkHasFields($parentId,'No',$id2)){
				$parentId=$this->findParentsId($parentId);
				if(!$this->checkHasFields($parentId,'No',$id2)){
					$parentId=$this->findParentsId($parentId);
					$this->checkHasFields($parentId,'No',$id2);
				}
			}
		}
	}
	
	function fetchadditionalfields_details($id=null,$id2=null){
		$this->layout=false;
		if(!$this->checkHasFields($id,"",$id2)){
			$parentId=$this->findParentsId($id);
			if(!$this->checkHasFields($parentId,'No',$id2)){
				$parentId=$this->findParentsId($parentId);
				if(!$this->checkHasFields($parentId,'No',$id2)){
					$parentId=$this->findParentsId($parentId);
					$this->checkHasFields($parentId,'No',$id2);
				}
			}
		}
	}
	function fetchadditionalfields($id=null,$id2=null){
		$this->layout=false;
		if(!$this->checkHasFields($id,"",$id2)){
			$parentId=$this->findParentsId($id);
			if(!$this->checkHasFields($parentId,'No',$id2)){
				$parentId=$this->findParentsId($parentId);
				if(!$this->checkHasFields($parentId,'No',$id2)){
					$parentId=$this->findParentsId($parentId);
					$this->checkHasFields($parentId,'No',$id2);
				}
			}
		}
	}
	
	function fetch_labels_fields_details($id=null,$id2=null,$id3=null){
		$fields=$this->Field->fetch_labels_fields_details($id,$id2,$id3);
		$this->set(compact('fields'));
	}
	function fetch_labels_fields($id=null,$id2=null,$id3=null){
		$fields=$this->Field->fetch_labels_fields($id,$id2,$id3);
		$this->set(compact('fields'));
	}
	
	function fetchsizes($id=null){
		$this->layout=false;
		$this->Category->bindModel(array('hasMany' => array('Sizelabel' => array(
			'className' => 'Sizelabel',
			'foreignKey' => 'category_id'))));
		$options['conditions'] = array('Category.id' => $id);
		$this->Category->Behaviors->attach('Containable');
        $this->Category->contain('Sizelabel','Sizetitle','Sizetitle.Sizevalue');
		$this->data['category_sizes']=$this->Category->find('all', $options);
	}
	function fetchsizes_edit($id=null,$id2=null){
		$this->layout=false;
		$this->Category->bindModel(array('hasMany' => array('Sizelabel' => array(
			'className' => 'Sizelabel',
			'foreignKey' => 'category_id'))));
		$options['conditions'] = array('Category.id' => $id);
		$this->Category->Behaviors->attach('Containable');
        $this->Category->contain('Sizelabel','Sizetitle','Sizetitle.Sizevalue');
		$this->data['category_sizes']=$this->Category->find('all', $options);
		
		$options['conditions']=array('Sizetitle.category_id'=>$id);
		$options['order']=array('Sizetitle.id asc');		
		$this->data['Size'] = $this->Sizetitle->find('all',$options);
		
		$options['conditions']=array('Sizelabel.category_id'=>$id);
		$options['order']=array('Sizelabel.id asc');
		$this->data['Sizelabel'] = $this->Sizelabel->find('all',$options);
		if(!empty($id2))
		{
			$options['conditions'] = array('ProductSize.product_id'=>$id2,'ProductSize.category_id'=>$id);
			$options['fields'] = array('ProductSize.id','ProductSize.sizevalue_id','ProductSize.sizetitle_id','ProductSize.sizelabel_id','ProductSize.category_id');
			$options['order']=array('Sizetitle.id asc');
			$this->data['selected_size'] = $this->ProductSize->find('all',$options);
		}
	}
	
	function chkHasParent($id=null){
		$this->Category->recursive=-1;
		$parent_id=$this->Category->findById($id,array('parent_id'));
                if($parent_id['Category']['parent_id']>0){
			$parent_id_label2=$this->Category->findById($parent_id['Category']['parent_id'],array('parent_id'));			
			$subcat['label2']="Yes";
			$subcat['label3']="No";
			$subcat['label4']="No";			
			$subcat['catid_label2']=$parent_id['Category']['parent_id'];
			$subcat['catid_label3']=$id;
				
			if($parent_id_label2['Category']['parent_id']>0){
				$parent_id_label3=$this->Category->findById($parent_id_label2['Category']['parent_id'],array('parent_id'));			
				$subcat['label2']="Yes";
				$subcat['label3']="Yes";
				$subcat['label4']="No";
				$subcat['catid_label2']=$parent_id_label2['Category']['parent_id'];
				$subcat['catid_label3']=$parent_id['Category']['parent_id'];
				$subcat['catid_label4']=$id;
			}
			if(isset($parent_id_label3['Category']['parent_id']) && $parent_id_label3['Category']['parent_id']>0){
				$parent_id_label4=$this->Category->findById($parent_id_label3['Category']['parent_id'],array('parent_id'));			
				$subcat['label2']="Yes";
				$subcat['label3']="Yes";
				$subcat['label4']="Yes";
				$subcat['catid_label2']=$parent_id_label3['Category']['parent_id'];
				$subcat['catid_label3']=$parent_id_label2['Category']['parent_id'];
				$subcat['catid_label4']=$parent_id['Category']['parent_id'];
				$subcat['catid_label5']=$id;
			}	
		}else{
			$subcat['label2']="No";
			$subcat['label3']="No";
			$subcat['label4']="No";
			$subcat['catid_label2']=$id;
		}	
		return $subcat;
	}


        function breadcrumchkHasParent($id=null){
            $this->layout=null;
            $this->autoRender=false;
		$this->Category->recursive=-1;
		$parent_id=$this->Category->findById($id,array('parent_id','category_name'));
		if($parent_id['Category']['parent_id']>0){
			$parent_id_label2=$this->Category->findById($parent_id['Category']['parent_id'],array('parent_id','category_name'));
			$subcat['label']="2";
                        $subcat['catname_label1']=$parent_id_label2['Category']['category_name'];
			$subcat['catid_label1']=$parent_id['Category']['parent_id'];
                        $subcat['catname_label2']=$parent_id['Category']['category_name'];
			$subcat['catid_label2']=$id;
	if($parent_id_label2['Category']['parent_id']>0){
				$parent_id_label3=$this->Category->findById($parent_id_label2['Category']['parent_id'],array('parent_id','category_name'));
				$subcat['label']="3";
				$subcat['catname_label1']=$parent_id_label3['Category']['category_name'];
                                $subcat['catid_label1']=$parent_id_label2['Category']['parent_id'];
                                $subcat['catname_label2']=$parent_id_label2['Category']['category_name'];
                                $subcat['catid_label2']=$parent_id['Category']['parent_id'];
                                $subcat['catname_label3']=$parent_id['Category']['category_name'];
                                $subcat['catid_label3']=$id;
			}
			if(isset($parent_id_label3['Category']['parent_id']) && $parent_id_label3['Category']['parent_id']>0){
				$parent_id_label4=$this->Category->findById($parent_id_label3['Category']['parent_id'],array('parent_id','category_name'));
				$subcat['label']="4";
				$subcat['catname_label1']=$parent_id_label4['Category']['category_name'];
                                $subcat['catid_label1']=$parent_id_label3['Category']['parent_id'];
                                $subcat['catname_label2']=$parent_id_label3['Category']['category_name'];
                                $subcat['catid_label2']=$parent_id_label2['Category']['parent_id'];
                                $subcat['catname_label3']=$parent_id_label2['Category']['category_name'];
                                $subcat['catid_label3']=$parent_id['Category']['parent_id'];
                                $subcat['catname_label4']=$parent_id['Category']['category_name'];
                                $subcat['catid_label4']=$id;
			}
		}else{
			$subcat['label']="1";
                        $subcat['catname_label1']=$parent_id['Category']['category_name'];
			$subcat['catid_label1']=$id;
		}
                return $subcat;
	}
        
	function fetchshippingmethod($id = null,$id2 = null){
		$this->layout=false;
		$this->Shipping->recursive=-1;
		$shippings=$this->Shipping->find("all",array("conditions"=>array("Shipping.category_id"=>$id,"shipping_destination"=>"National")));		
		$handalingtimes=$this->HandleTime->find("all");				
		$this->set(compact('shippings', 'handalingtimes'));	
		$this->data['selected_handletime']="0";	
		if(!empty($id2)){
			$this->data['ProductShippings']=$this->ProductShipping->find('all',array('conditions'=>array('ProductShipping.product_id'=>$id2)));
			$this->Product->recursive=-1;
			$productshippings=$this->Product->find('first',array('fields'=>array('handletime_id','handale_additional_info'),'conditions'=>array('Product.id'=>$id2)));
			$this->data['selected_handletime']=$productshippings['Product']['handletime_id'];
			$this->data['handale_additional_info']=$productshippings['Product']['handale_additional_info'];
		}
	}
	function getshippingcost($id = null){
		$this->layout=false;
		$this->Category->recursive=-1;
		$shippings=$this->Category->findById($id,array('fields'=>'shipping_cost'));						
		$return_arr['shipping_cost']=$shippings['Category']['shipping_cost'];
		echo json_encode($return_arr);
		$this->autoRender=false;
	}
	function deleteinternationalshippingmethods($id=null){
		$this->layout=false;
		
		if($this->ProductInternationalShipping->delete($id)){
			$return_arr['message']="Yes";
		}else{	
			$return_arr['message']="No";
		}		
		$return_arr['RowId']=$id;
		echo json_encode($return_arr);
		$this->autoRender=false;
	}
	function deleteshippingmethods($id=null,$id2=null){
		$this->layout=false;
		
		if($this->ProductShipping->delete($id)){
			$return_arr['message']="Yes";
		}else{
			$return_arr['message']="No";
		}
		$return_arr['RowId']=$id;
		echo json_encode($return_arr);
		$this->autoRender=false;
	}
	function deletethumbimage($id=null){
		$this->layout=false;
		$this->ProductImage->recursive=-1;
		$ProductImage=$this->ProductImage->findById($id);
		$this->Uploader->delete('img/imagecache/'.$ProductImage['ProductImage']['image']);
		$this->Uploader->delete('img/thumbs/'.$ProductImage['ProductImage']['image']);
		$this->Uploader->delete('img/uploads/'.$ProductImage['ProductImage']['image']);
		if($this->ProductImage->delete($id)){
			$return_arr['message']="Yes";
		}else{
			$return_arr['message']="No";
		}
		$return_arr['RowId']=$id;
		echo json_encode($return_arr);
		$this->autoRender=false;
	}
	function getshippingmethods($id = null){
		$this->layout=false;
		$this->Shipping->recursive=-1;
		$shippings=$this->Shipping->findAllById($id);
		echo json_encode($shippings[0]['Shipping']);
		$this->autoRender=false;
	}
	
	function fetchvaluearray($id=null){
		$this->layout=false;
		$this->loadModel("Sizevalue");
		$this->Sizevalue->recursive=-1;
		$valuearrays=$this->Sizevalue->findAllBySizetitleId($id);		
		$html="";
		foreach($valuearrays as $valuearray){
			$html.='<option value="'.$valuearray['Sizevalue']['id'].'">'.$valuearray['Sizevalue']['size_value'].'</option>';
		}
		echo $html;
		$this->autoRender=false;
	}
        
	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for product', true));
			$this->redirect(array('action'=>'index'));
		}
                
		if ($this->Product->delete($id)) {
			$this->Session->setFlash(__('Product deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Product was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}

        function endselected($id = null) {
            $this->layout=FALSE;
            $this->autoRender=false;
		if (!$id) {
			//$this->Session->setFlash(__('Invalid id for product', true));
			//$this->redirect(array('action'=>'index'));
		}
	    $this->Product->id=$id;
            $this->Product->saveField('products_status', 'Unsold');
        }

        function activeselected($id = null) {
            $this->layout=FALSE;
            $this->Product->recursive=-1;
            $chek=$this->Product->find('first',array('conditions'=>array('Product.id'=>$id),'fields'=>array('Product.pendingtounsold')));
            
if($chek['Product']['pendingtounsold']=='No'){
            $this->Product->id=$id;
            $this->Product->saveField('products_status', 'Active');
        }else{
            $this->Product->id=$id;
            $this->Product->saveField('products_status', 'Pending');
        }
            $this->autoRender=false;
	}

        function unsoldselected($id = null) {
            $this->layout=FALSE;            
            $this->data['Product']['pendingtounsold']='Yes';
            $this->data['Product']['products_status']='Unsold';
            $this->Product->id=$id;
            $this->Product->save($this->data);
            $this->autoRender=false;
                }

       function end($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for product', true));
			$this->redirect(array('action'=>'index'));
		}

		if ($id) {
                        $this->Product->id=$id;
                        $this->Product->saveField('products_status', 'Unsold');
			$this->Session->setFlash(__('Product Ended successfully', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Product was not End', true));
		$this->redirect(array('action' => 'index'));
	}
       
  function product_disapproved($pid=null){
    $this->layout=FALSE;
    if(!empty ($this->data)){
       $this->data['Product']['disapproved_date']=date("Y-m-d H:i:s");
            $this->data['Product']['approved_id']=$this->Auth->user('id');;
            $this->data['Product']['products_status']='Disapproved';
            $this->Product->save($this->data);
            $this->Product->Behaviors->attach('Containable');
	    $this->Product->contain('User.username', 'User.email');
	    $products=$this->Product->find('first',array('conditions' => array('Product.id' => $this->data['Product']['id']),
                'fields'=>array('Product.products_title','Product.user_id','Product.id')));
$this->loadModel('Aprovalnotification');
             $chk=$this->Aprovalnotification->find('first',array('conditions'=>array('Aprovalnotification.user_id'=>$products['Product']['user_id'])));
                if($chk['Aprovalnotification']['status']==1){
////////for send email////////
            $this->Email->to = $products['User']['email'];
            //$this->Email->bcc = array('secret@example.com');
            $this->Email->subject = 'About Disapproval of your product--('.$products['Product']['products_title'].'),(Item # '.$this->data['Product']['id'].')';
            //$this->Email->replyTo = 'noreply@authenticavenue.com';
            $this->Email->from = $this->Auth->user('username').'<'.$this->Auth->user('email').'>';
            $this->Email->template = 'product_disapproved'; // note no '.ctp'
            //Send as 'html', 'text' or 'both' (default is 'text')
            $this->Email->sendAs = 'html'; // because we like to send pretty mail
            //Set view variables as normal
            $this->set('reason', $this->data['Product']['product_comments']);
            $this->set('products', $products);
            $this->Email->send();
                }
            $this->render('disapprovedsuccess');
        }else{
        $this->set('pid',$pid);
    }
  }

  function product_disapproved_selected(){
    $this->layout=FALSE;
    if(!empty ($this->data)){
        $productids=explode(',', $this->data['Product']['id']);
            foreach($productids as $productids_value){
            $this->data['Product']['id']=$productids_value;
            $this->data['Product']['disapproved_date']=date("Y-m-d H:i:s");
            $this->data['Product']['approved_id']=$this->Auth->user('id');;
            $this->data['Product']['products_status']='Disapproved';
            //$this->Product->create();
            $this->Product->save($this->data);
            $this->Product->Behaviors->attach('Containable');
	    $this->Product->contain('User.username', 'User.email');
	    $products=$this->Product->find('first',array('conditions' => array('Product.id' => $productids_value),
                'fields'=>array('Product.products_title','Product.user_id','Product.id')));
            $this->loadModel('Aprovalnotification');
             $chk=$this->Aprovalnotification->find('first',array('conditions'=>array('Aprovalnotification.user_id'=>$products['Product']['user_id'])));
                if($chk['Aprovalnotification']['status']==1){
            
             ////////for send email////////
            $this->Email->to = $products['User']['email'];
            //$this->Email->bcc = array('secret@example.com');
            $this->Email->subject = 'About Disapproval of your product--('.$products['Product']['products_title'].'),(Item # '.$productids_value.')';
            //$this->Email->replyTo = 'noreply@authenticavenue.com';
            $this->Email->from = $this->Auth->user('username').'<'.$this->Auth->user('email').'>';
            $this->Email->template = 'product_disapproved'; // note no '.ctp'
            //Send as 'html', 'text' or 'both' (default is 'text')
            $this->Email->sendAs = 'html'; // because we like to send pretty mail
            //Set view variables as normal
             $this->set('reason', $this->data['Product']['product_comments']);
            $this->set('products', $products);
              //Do not pass any args to send()
            $this->Email->send();
                }
            //////////////////////////////
                }        
            $this->render('disapprovedsuccess');
        }
  }

 function product_approved($pid=null){
            $this->layout=FALSE;
            $this->Product->id=$pid;
            $this->data['Product']['approved_date']=date("Y-m-d H:i:s");
            $this->data['Product']['approved_id']=$this->Auth->user('id');;
            $this->data['Product']['products_status']='Approved';
            $this->Product->save($this->data);
$this->Product->Behaviors->attach('Containable');
	    $this->Product->contain('User.username', 'User.email');
	    $products=$this->Product->find('first',array('conditions' => array('Product.id' => $pid),
                'fields'=>array('Product.products_title','Product.user_id','Product.id')));

             $this->loadModel('Aprovalnotification');
             $chk=$this->Aprovalnotification->find('first',array('conditions'=>array('Aprovalnotification.user_id'=>$products['Product']['user_id'])));
                if($chk['Aprovalnotification']['status']==1){
                  ////////for send email////////
            $this->Email->to = $products['User']['email'];
            //$this->Email->bcc = array('secret@example.com');
            $this->Email->subject = 'About approval of your product--('.$products['Product']['products_title'].'),(Item # '.$pid.')';
            //$this->Email->replyTo = 'noreply@authenticavenue.com';
            $this->Email->from = $this->Auth->user('username').'<'.$this->Auth->user('email').'>';
            $this->Email->template = 'product_approved'; // note no '.ctp'
            //Send as 'html', 'text' or 'both' (default is 'text')
            $this->Email->sendAs = 'html'; // because we like to send pretty mail
            //Set view variables as normal
            $this->set('products', $products);
            $this->Email->send();
                }
            $this->autoRender=false;
        }

        function backstage_index() {
		$this->Product->recursive = 0;		
		$this->set('products', $this->paginate());
	}

	function backstage_view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid product', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('product', $this->Product->read(null, $id));
	}
	
	function block()	
	{
		$this->layout=false;
		if(isset($this->data)){
			$d=base64_encode(serialize($this->data));
			$this->Session->write('blockCountry', $d);
			$return_array['msg']="Yes";
			echo json_encode($return_array);
		}else{
			$return_array['msg']="No";
			echo json_encode($return_array);
		}
		$this->autoRender=false;
	}
	
	function blockcountry($id=null){
		$this->layout=false;        
		$this->loadModel('Country');	
		$this->loadModel('Continent');	
		$this->loadModel('BlockCountryShip');	
        $this->Country->recursive = -1;
        $this->BlockCountryShip->recursive = -1;
		
        if(!empty($id))   
		$check = $this->BlockCountryShip->find('all', array('conditions' => array('BlockCountryShip.product_id' =>$id,'BlockCountryShip.seller_id' => $this->Auth->user('id')),'fields'=>array('country_id')));
		
		$i=0;
		if(!empty ($check)){
		foreach ($check as $chkv):
			$cid[$i]=$chkv['BlockCountryShip']['country_id'];
		$i++;
		endforeach;
		}else{
			$cid=array();
		}
		
		if(!empty($cid)){
			$this->set('cid',$cid);
			$this->set('cna', $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' =>$id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>1))));
			$this->set('na', $this->Country->find('all',array('conditions'=>array('Country.continent_id'=>1))));
			$this->set('csa', $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' =>$id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>2))));
			$this->set('sa', $this->Country->find('all',array('conditions'=>array('Country.continent_id'=>2))));
			$this->set('cep', $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' =>$id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>3))));
			$this->set('ep', $this->Country->find('all',array('conditions'=>array('Country.continent_id'=>3))));
			$this->set('cas', $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' =>$id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>4))));
			$this->set('as', $this->Country->find('all',array('conditions'=>array('Country.continent_id'=>4))));
			$this->set('coc', $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' =>$id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>5))));
			$this->set('oc', $this->Country->find('all',array('conditions'=>array('Country.continent_id'=>5))));
			$this->set('caf', $this->BlockCountryShip->find('count', array('conditions' => array('BlockCountryShip.product_id' =>$id,'BlockCountryShip.seller_id' => $this->Auth->user('id'),'BlockCountryShip.continent_id' =>6))));
			$this->set('af', $this->Country->find('all',array('conditions'=>array('Country.continent_id'=>6))));
		}
		else{
			$this->set('cid',$cid);
			$this->set('cna',0);
			$this->set('na', $this->Country->find('all',array('conditions'=>array('Country.continent_id'=>1))));
			$this->set('csa',0);
			$this->set('sa', $this->Country->find('all',array('conditions'=>array('Country.continent_id'=>2))));
			$this->set('cep',0);
			$this->set('ep', $this->Country->find('all',array('conditions'=>array('Country.continent_id'=>3))));
			$this->set('cas',0);
			$this->set('as', $this->Country->find('all',array('conditions'=>array('Country.continent_id'=>4))));
			$this->set('coc',0);
			$this->set('oc', $this->Country->find('all',array('conditions'=>array('Country.continent_id'=>5))));
			$this->set('caf',0);
			$this->set('af', $this->Country->find('all',array('conditions'=>array('Country.continent_id'=>6))));
		}
	}
	
	function backstage_add() {
		
		if (!empty($this->data)) {
			$this->Product->create();
			if ($this->Product->save($this->data)) {
				$this->Session->setFlash(__('The product has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The product could not be saved. Please, try again.', true));
			}
		}
		$users = $this->Product->User->find('list');
		$categories = $this->Product->Category->find('list');
		$this->set(compact('users', 'categories'));
	}

	function backstage_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid product', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Product->save($this->data)) {
				$this->Session->setFlash(__('The product has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The product could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Product->read(null, $id);
		}
		$users = $this->Product->User->find('list');
		$categories = $this->Product->Category->find('list');
		$this->set(compact('users', 'categories'));
	}

	function backstage_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for product', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Product->delete($id)) {
			$this->Session->setFlash(__('Product deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		
		$this->Session->setFlash(__('Product was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
        
    function success(){
		$this->layout=false;
	}

 function details($id=NULL) {
        $this->layout = 'details';
        //getting products
        $this->Product->recursive = 2;
        $this->Product->Behaviors->attach('Containable');
        $this->Product->contain('User.Group', 'User.State', 'User.Country', 'Category', 'Brand', 'ProductImage', 'HandleTime');
        $products = $this->Product->find('first', array('conditions' => array('OR' => array(array('Product.products_status' => 'Active'), array('Product.products_status' => 'Approved')), 'Product.products_expiredDate >=' => date("Y-m-d H:i:s"), 'Product.id' => $id)));
        $this->loadModel('BlockCountry');
        $blockCountries = $this->BlockCountry->find('all', array('conditions' => array('BlockCountry.seller_id' => $products['Product']['user_id']), 'order' => array('Country.name', 'Country.name ASC')));
        if (count($blockCountries) != 0) {
            $this->set('blockCountries', $blockCountries);
            //check if current user from block countries
            foreach ($blockCountries as $blockCountry) {
                if (array_search($this->Auth->user('country_id'), $blockCountry['Country']) !== FALSE) {
                    $this->render('block_countries');
                    return;
                }
            }
        }
        //calulate commition and negotiations
        $buyerId = $this->Auth->User('id') == NULL ? 0 : $this->Auth->User('id');
        $this->set('commition', $this->Product->commition($products, $buyerId));
        $this->Product->query("update authentic_products set `products_views`=`products_views`+1 where `id`=$id;");
        $this->Categorybrand->Behaviors->attach('Containable');
        $this->Categorybrand->contain('Brand.brand_description');
        $categoryBrandCondition = $this->Categorybrand->find('first', array('conditions' => array('Brand.id' => $products['Product']['global_conditions'], 'Categorybrand.brand_type' => 'condition', 'Categorybrand.category_id' => $products['Product']['category_id'])));
        $this->set('conditions', $categoryBrandCondition);
        $this->set('styles', $this->Categorybrand->find('first', array('conditions' => array('Brand.id' => $products['Product']['global_styles'], 'Categorybrand.brand_type' => 'style'), 'Categorybrand.category_id' => $products['Product']['category_id'])));
        $this->set('brands', $this->Categorybrand->find('first', array('conditions' => array('Brand.id' => $products['Product']['global_brands'], 'Categorybrand.brand_type' => 'brand'), 'Categorybrand.category_id' => $products['Product']['category_id'])));
		$this->set('productFields', $this->Field->find('all', array('conditions' => array('Field.category_id' => $products['Product']['category_id']))));       
		
		$this->ProductSize->Behaviors->attach('Containable');
        $this->ProductSize->contain('Sizetitle','Sizevalue','Sizelabel');
        $options['order'] = array('ProductSize.sizelabel_id DESC');
        $options['conditions'] = array('ProductSize.product_id' => $products['Product']['id'], 'ProductSize.category_id' => $products['Product']['category_id']);
        $options['fields'] = array('ProductSize.*','Sizevalue.size_value','Sizetitle.size_title','Sizelabel.size_label');
        $this->data['selected_size'] = $this->ProductSize->find('all', $options);
		
        $this->set('domesticShipping', $this->ProductShipping->find('all', array('conditions' => array('ProductShipping.product_id' => $products['Product']['id']))));
        $this->ProductInternationalShipping->unbindModel(array('belongsTo' => array('Continent')));
        $productinternationalshippings = $this->ProductInternationalShipping->find('all', array('conditions' => array('ProductInternationalShipping.product_id' => $id)));
        $i = 0;
        $this->loadModel("Continent");
        $this->Continent->recursive = -1;
        foreach ($productinternationalshippings as $productinternationalshipping):
            if ($productinternationalshipping['ProductInternationalShipping']['continent_id'] != "worldwide") {
                $conID = explode(",", $productinternationalshipping['ProductInternationalShipping']['continent_id']);
                $flag = 1;
                $continent = "";
                foreach ($conID as $continentID) {
                    $continent_name = $this->Continent->find("first", array("conditions" => array("id" => $continentID), "fields" => array("name")));
                    if ($flag == 1) {
                        $continent.=$continent_name['Continent']['name'];
                        $flag = 0;
                    }
                    else
                        $continent.=", " . $continent_name['Continent']['name'];
                }
                $productinternationalshippings[$i]['ProductInternationalShipping']['continent_id'] = $continent;
            }
            else
                $productinternationalshippings[$i]['ProductInternationalShipping']['continent_id'] = $productinternationalshipping['ProductInternationalShipping']['continent_id'];
            $i++;
        endforeach;
        $this->set('internationalShipping', $productinternationalshippings);
        $this->set('products', $products);
        $this->set('item', $this->Category->categoryArray());
        $this->loadModel('Rating');
        $this->set('productRating', $this->Rating->checkRating($products['User']['id'], $products['Product']['id']));
        $this->loadModel('Returnpolicy');
        if ($products['Product']['products_returnPolicyType'] == "Yes") {
            $returnpolicies = $this->Returnpolicy->findBySellerId($products['Product']['user_id']);
            $returnpolicy = $returnpolicies['Returnpolicy']['policy'];
        } else {
            $returnpolicy = $products['Product']['products_returnPolicy'];
        }
        $this->set('returnpolicy', $returnpolicy);
        if ($this->Auth->User('id') != NULL) {
            $this->loadModel('Order');
            $countvalue = $this->Order->find('count', array('conditions' => array('Order.user_id' => $this->Auth->User('id'), 'Order.product_id' => $id)));
            $this->set('alreadybuy', $countvalue);
            if ($countvalue > 0) {
                $buyingdate = $this->Order->find('first', array('conditions' => array('Order.user_id' => $this->Auth->User('id'), 'Order.product_id' => $id), 'recursive' => -1, 'fields' => array('Order.id', 'Order.add_date')));
                $this->set('buyingdate', $buyingdate);
            }
        }
    }
        
        function ratingSave() {
            $this->layout = FALSE;
            $this->autoRender = FALSE;
            $this->loadModel('Rating');
            if ($this->Rating->save($this->data)) {
                echo 'Feedback has been submitted successfully.';
            } else {
                echo 'Feedback does not save. Please try again.';
            }
        }

        function feedback_chk_byuser($pid,$userid){
            $this->layout=FALSE;
            $this->autoRender=FALSE;
            $this->loadModel('Rating');
            return $this->Rating->find('count', array('conditions' => array('Rating.buyer_id' => $userid,'Rating.product_id' => $pid)));
        }

	function addnote($pid=null){
		$this->layout = false;
		$this->data['Note']['product_id']=$pid;
                $this->data['Note']['user_id']=$this->Auth->user('id');
		$this->Note->save($this->data);
		$this->set('pid', $pid);
	}

        function updatenote($id=null){
		$this->layout = false;
                $this->autoRender=false;
                $this->Note->id=$id;
                $this->Note->save($this->data);
                echo 'success';
		//$this->set('pid', $pid);
	}


        function addnote_pending($pid=null,$sid=null){
		$this->layout = false;
		if(!empty ($this->data)){
		if(!empty ($this->data['Note']['id'])){
                $this->Note->id=$this->data['Note']['id'];
                $this->Note->save($this->data);
                }else
                {
                $this->data['Note']['user_id']=$this->Auth->user('id');
		$this->Note->save($this->data);
                   }
                   $this->Render('notesuccess');
                }else{
                 $this->set('pid',$pid);
                 $this->set('sid',$sid);
                }
	}

   function addnote_selected($pid=null, $sid=null) {
        $this->layout = false;
        if (!empty($this->data)) {
         if (!empty($this->data['Note']['product_ids'])) {
                $productids = explode(',', $this->data['Note']['product_ids']);
                foreach ($productids as $productids_value) {
                    $this->Note->recursive = -1;
                    $ise = $this->Note->find('first', array('fields' => array('Note.id'), 'conditions' => array('Note.user_id' => $this->Auth->user('id'), 'Note.product_id' => $productids_value)));
                    if (!empty($ise)){
                        $this->data['Note']['id'] = $ise['Note']['id'];
                        $this->Note->create();
                        $this->Note->save($this->data);
                    }else{
                        $this->Note->create();
                        $this->data['Note']['product_id'] = $productids_value;
                        $this->data['Note']['user_id'] = $this->Auth->user('id');
                        $this->Note->save($this->data);
                    }
                }
                $this->Render('notesuccess');
            } else {
                $this->set('productempty', 'Please select at least one product.');
            }
        }
    }

        function addnote_reportitem($pid=null, $sid=null) {
                    $this->layout = false;
                    $this->loadModel('Reportnote');
                    if (!empty($this->data)) {
                          if (!empty($this->data['Reportnote']['product_ids'])) {
                            $productids = explode(',', $this->data['Reportnote']['product_ids']);
                            foreach ($productids as $productids_value) {
                                $this->Reportnote->recursive = -1;
                                $ise = $this->Reportnote->find('first', array('fields' => array('Reportnote.id'), 'conditions' => array('Reportnote.user_id' => $this->Auth->user('id'), 'Reportnote.product_id' => $productids_value)));
                                if (!empty($ise)) {
                                    $this->data['Reportnote']['id'] = $ise['Reportnote']['id'];
                                    $this->Reportnote->create();
                                    $this->Reportnote->save($this->data);
                                }else{
                                    $this->Reportnote->create();
                                    $this->data['Reportnote']['product_id'] = $productids_value;
                                    $this->data['Reportnote']['user_id'] = $this->Auth->user('id');
                                    $this->Reportnote->save($this->data);
                                }
                            }
                         $this->Render('notesuccess');
                        } else {
                            $this->set('productempty', 'Please select at least one product.');
                        }
                    }
                }

  function addnote_reporteditem($pid=null) {
        $this->layout = false;
        $this->loadModel('Reportnote');
        if (!empty($this->data)) {
            $this->Reportnote->recursive = -1;
            $ise = $this->Reportnote->find('first', array('fields' => array('Reportnote.id'), 'conditions' => array('Reportnote.user_id' => $this->Auth->user('id'), 'Reportnote.product_id' => $this->data['Reportnote']['product_id'])));
            if(!empty($ise)) {
                $this->data['Reportnote']['id'] = $ise['Reportnote']['id'];
                $this->Reportnote->create();
                $this->Reportnote->save($this->data);
            }else{
                $this->Reportnote->create();
                $this->data['Reportnote']['user_id'] = $this->Auth->user('id');
                $this->Reportnote->save($this->data);
            }
            $this->Render('notesuccess');
        }
        $this->set('pid', $pid);
    }

   function addsoldnote_selected($pid=null, $sid=null) {
        $this->layout = false;
        $this->loadModel('Soldnote');
        if (!empty($this->data)) {
            if (!empty($this->data['Soldnote']['product_ids'])) {
                $productids = explode(',', $this->data['Soldnote']['product_ids']);
                foreach ($productids as $productids_value) {
                    $this->Soldnote->recursive = -1;
                    $ise = $this->Soldnote->find('first', array('fields' => array('Soldnote.id'), 'conditions' => array('Soldnote.user_id' => $this->Auth->user('id'), 'Soldnote.product_id' => $productids_value)));
                    if (!empty($ise)) {
                        $this->data['Soldnote']['id'] = $ise['Soldnote']['id'];
                        $this->Soldnote->create();
                        $this->Soldnote->save($this->data);
                    } else {
                        $this->Soldnote->create();
                        $this->data['Soldnote']['product_id'] = $productids_value;
                        $this->data['Soldnote']['user_id'] = $this->Auth->user('id');
                        $this->Soldnote->save($this->data);
                    }
                }
            $this->Render('notesuccess');
            }else{
                $this->set('productempty', 'Please select at least one product.');
            }
        }
    }

	function getnote($pid=null,$uid=null,$flag=null){
		$this->layout = false;
		$this->autoRender=false;
		if($flag=="1"){
			$this->Note->Behaviors->attach('Containable');
			$this->Note->contain('User.username');
			return $this->Note->find('all', array('conditions' => array('Note.product_id' => $pid,'Note.user_id !=' => $uid)));
		}
		elseif($flag=="2"){
			$this->Note->Behaviors->attach('Containable');
			$this->Note->contain('User.username');
			return $this->Note->find('all', array('conditions' => array('Note.product_id' => $pid,'Note.user_id' => $uid)));
		}
		else{
			$this->Note->recursive=-1;
			return $this->Note->findAllByProductId($pid);
		}
	  }

          function getnotereport($pid=null,$uid=null){
		$this->layout = false;
		$this->autoRender=false;
                $this->loadModel('Reportnote');
                $this->Reportnote->Behaviors->attach('Containable');
                $this->Reportnote->contain('User.username');
                return $this->Reportnote->find('all', array('conditions' => array('Reportnote.product_id' => $pid,'Reportnote.user_id !=' => $uid)));
    	  }

          function getsoldnote($pid=null,$uid=null,$flag=null){
		$this->layout = false;
		$this->autoRender=false;
                $this->loadModel('Soldnote');
                $this->Soldnote->Behaviors->attach('Containable');
                $this->Soldnote->contain('User.username');
       return $this->Soldnote->find('all', array('conditions' => array('Soldnote.product_id' => $pid,'Soldnote.user_id' => $uid)));
	  }

        function ask_a_question($id){
              $this->layout = false;
              $this->Product->recursive=2;
              $this->Product->Behaviors->attach('Containable');
              $this->Product->contain('User.Group');
              $this->set('qData', $this->Product->find('first', array('conditions'=>array('Product.id'=>$id))));
          }
          
         function sendMessege(){
              $this->layout = false;
              $this->autoRender=false;
              $this->loadModel('Message');
              $this->loadModel('MessageTrack');
              if(isset ($this->data))
              {
                  $this->Message->save($this->data['Message']);
                  $this->data['MessageTrack']['message_id']=$this->Message->getLastInsertId();
                  $this->MessageTrack->save($this->data['MessageTrack']);
                  $this->data['MessageTrack']['id']=NULL;
                  $this->data['MessageTrack']['msg_type']=0;
                  $this->MessageTrack->save($this->data['MessageTrack']);
              }
          }

      function advance_search() {
        $this->layout = 'innerhome';
        $this->set('item', $this->Category->categoryArray());
        $this->set('homePageContent', $this->Product->homePageProducts($this->Category->randomCategory()));
        $categories = $this->Product->Category->find('list');
        $this->set(compact('categories'));
if (!empty($_POST)) {
            $this->set('keywords', $_POST['keywords']);
            $this->Product->Behaviors->attach('Containable');
            $this->Product->contain('User.username');
            if ($_POST['sortby'] == 1) {
                $fild = 'Product.products_expiredDate';
                $ord = 'ASC';
            } elseif ($_POST['sortby'] == 2) {
                $fild = 'Product.products_createDate';
                $ord = 'DESC';
            } elseif ($_POST['sortby'] == 3) {
                $fild = 'Product.products_price';
                $ord = 'DESC';
            } else {
                $fild = 'Product.products_price';
                $ord = 'ASC';
            }
            $flds = array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.products_views', 'Product.products_price', 'Product.products_status', 'DATEDIFF(products_expiredDate,now()) AS totaldays');
            if (isset($_POST['com_list']) AND isset($_POST['tle_des'])) {
                if (!empty($this->data['Product']['categories'])) {
                    $prms = array(
                        'conditions' => array(
                            'Product.category_id' => $this->data['Product']['categories'],
                            'OR' => array('Product.products_status !=' => 'Pending',
                                'Product.products_status !=' => 'Disapproved'),
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                            'OR' => array('Product.products_title like' => '%' . $_POST['keywords'] . '%',
                                'Product.products_description like' => '%' . $_POST['keywords'] . '%')),
                        'order' => array($fild => $ord),
                        'fields' => $flds,
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                } else {
                    $prms = array(
                        'conditions' => array(
                            'OR' => array('Product.products_status !=' => 'Pending',
                                'Product.products_status !=' => 'Disapproved'),
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                            'OR' => array('Product.products_title like' => '%' . $_POST['keywords'] . '%',
                                'Product.products_description like' => '%' . $_POST['keywords'] . '%')),
                        'order' => array($fild => $ord),
                        'fields' => $flds,
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                }
            } elseif (isset($_POST['com_list'])) {
                if (is_numeric($_POST['keywords'])) {
                    if (!empty($this->data['Product']['categories'])) {
                        $prms = array(
                            'conditions' => array(
                                'Product.category_id' => $this->data['Product']['categories'],
                                'OR' => array('Product.products_status !=' => 'Pending',
                                    'Product.products_status !=' => 'Disapproved'),
                                'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                                'Product.id' => $_POST['keywords']
                            ),
                            'order' => array($fild => $ord),
                            'fields' => $flds,
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    } else {
                        $prms = array(
                            'conditions' => array(
                                'Product.id' => $_POST['keywords'],
                                'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                                'OR' => array('Product.products_status !=' => 'Pending',
                                    'Product.products_status !=' => 'Disapproved')),
                            'order' => array($fild => $ord),
                            'fields' => $flds,
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    }
                } else {
                    if (!empty($this->data['Product']['categories'])) {
                        $prms = array(
                            'conditions' => array(
                                'OR' => array('Product.products_status !=' => 'Pending',
                                    'Product.products_status !=' => 'Disapproved'),
                                'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                                'Product.products_title like' => '%' . $_POST['keywords'] . '%',
                                'Product.category_id' => $this->data['Product']['categories']),
                            'order' => array($fild => $ord),
                            'fields' => $flds,
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    } else {
                        $prms = array(
                            'conditions' => array(
                                'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                                'OR' => array('Product.products_status !=' => 'Pending',
                                    'Product.products_status !=' => 'Disapproved'),
                                'Product.products_title like' => '%' . $_POST['keywords'] . '%'),
                            'order' => array($fild => $ord),
                            'fields' => $flds,
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    }
                }
            } elseif (isset($_POST['tle_des'])) {
                if (!empty($this->data['Product']['categories'])) {
                    $prms = array(
                        'conditions' => array(
                            'Product.category_id' => $this->data['Product']['categories'],
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                            'OR' => array('Product.products_status !=' => 'Pending',
                                'Product.products_status !=' => 'Disapproved'),
                            'OR' => array('Product.products_title like' => '%' . $_POST['keywords'] . '%',
                                'Product.products_description like' => '%' . $_POST['keywords'] . '%')),
                        'order' => array($fild => $ord),
                        'fields' => $flds,
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                } else {
                    $prms = array(
                        'conditions' => array('OR' => array(
                                'Product.products_status !=' => 'Pending',
                                'Product.products_status !=' => 'Disapproved'),
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                            'OR' => array('Product.products_title like' => '%' . $_POST['keywords'] . '%',
                                'Product.products_description like' => '%' . $_POST['keywords'] . '%')),
                        'order' => array($fild => $ord),
                        'fields' => $flds,
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                }
            } else {
                if (is_numeric($_POST['keywords'])) {
                    if (!empty($this->data['Product']['categories'])) {
                        $prms = array(
                            'conditions' => array(
                                'Product.id' => $_POST['keywords'],
                                'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                                'Product.category_id' => $this->data['Product']['categories'],
                                'OR' => array('Product.products_status !=' => 'Pending',
                                    'Product.products_status !=' => 'Disapproved'
                            )),
                            'order' => array($fild => $ord),
                            'fields' => $flds,
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    } else {
                        $prms = array(
                            'conditions' => array(
                                'Product.id' => $_POST['keywords'],
                                'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                                'OR' => array('Product.products_status !=' => 'Pending',
                                    'Product.products_status !=' => 'Disapproved'
                            )),
                            'order' => array($fild => $ord),
                            'fields' => $flds,
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    }
                } else {
                    if (!empty($this->data['Product']['categories'])) {
                        $prms = array(
                            'conditions' => array(
                                'OR' => array('Product.products_status !=' => 'Pending',
                                    'Product.products_status !=' => 'Disapproved'),
                                'Product.products_title like' => '%' . $_POST['keywords'] . '%',
                                'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                                'Product.category_id' => $this->data['Product']['categories']),
                            'order' => array($fild => $ord),
                            'fields' => $flds,
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    } else {
                        $prms = array(
                            'conditions' => array(
                                'OR' => array('Product.products_status !=' => 'Pending',
                                    'Product.products_status !=' => 'Disapproved'),
                                'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                                'Product.products_title like' => '%' . $_POST['keywords'] . '%'),
                            'order' => array($fild => $ord),
                            'fields' => $flds,
                            'contain' => array(
                                'User.username',
                                'Approver.username'
                            )
                        );
                    }
                }
            }
            $this->set('products', $this->Product->find('all', $prms));
            $this->set('viewresult', $_POST['view_result']);
            $this->render('search_result1');
        }
    }


    function search_result() {
        $this->layout = 'innerhome';
        $this->set('item', $this->Category->categoryArray());
        $this->set('homePageContent', $this->Product->homePageProducts($this->Category->randomCategory()));
        $categories = $this->Product->Category->find('list');
        $this->set(compact('categories'));
        if (!empty($_POST)) {
            $this->set('searchkey', $_POST['serchkey']);
            $this->Product->Behaviors->attach('Containable');
            $this->Product->contain('User.username');
            $flds = array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.products_views', 'Product.products_price', 'Product.products_status', 'DATEDIFF(products_expiredDate,now()) AS totaldays');
            if (is_numeric($_POST['serchkey'])) {
             if (!empty($_POST['cat_id'])) {

                    $prms = array(
                        'conditions' => array(
                            'Product.category_id' => $_POST['cat_id'],
                            'OR' => array('Product.products_status !=' => 'Pending',
                                'Product.products_status !=' => 'Disapproved'),
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                            'Product.id' => $_POST['serchkey']),
                        'order' => array('Product.id' => 'DESC'),
                        'fields' => $flds,
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                } else {

                    $prms = array(
                        'conditions' => array(
                            'OR' => array('Product.products_status !=' => 'Pending',
                                'Product.products_status !=' => 'Disapproved'),
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                            'Product.id' => $_POST['serchkey']),
                        'order' => array('Product.id' => 'DESC'),
                        'fields' => $flds,
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                }
            } else {
                if (!empty($_POST['cat_id'])) {
                    $prms = array(
                        'conditions' => array(
                            'OR' => array('Product.products_status !=' => 'Pending',
                                'Product.products_status !=' => 'Disapproved'),
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                            'Product.products_title like' => '%' . $_POST['serchkey'] . '%',
                            'Product.category_id' => $_POST['cat_id']),
                        'order' => array('Product.id' => 'DESC'),
                        'fields' => $flds,
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                } else {

                    $prms = array(
                        'conditions' => array(
                            'OR' => array('Product.products_status !=' => 'Pending',
                                'Product.products_status !=' => 'Disapproved'),
                            'Product.products_expiredDate >=' => date('Y-m-d H:i:s'),
                            'Product.products_title like' => '%' . $_POST['serchkey'] . '%'
                        ),
                        'order' => array('Product.id' => 'DESC'),
                        'fields' => $flds,
                        'contain' => array(
                            'User.username',
                            'Approver.username'
                        )
                    );
                }
            }
            $this->set('products', $this->Product->find('all', $prms));
        } else {
            echo 'invalid operation.';
            exit;
        }
    }
    function browsebycategory($cat_id=null,$sort=null) {
        $this->layout = 'innerhome';        
		$colors=$this->Field->find('all',array('conditions'=>array(
		'OR'=>array(
			array('Field.field_name like'=>'%Color%'),
			array('Field.field_name like'=>'%color%'),
			array('Field.field_name like'=>'%Colur%'),
			array('Field.field_name like'=>'%colur%'))
		),
		'fields'=>array('Field.id','Field.field_value'),'order'=>'Field.id  asc','recursive'=>'-1'));
		foreach($colors as $color){
			
		};
        $this->set('item', $this->Category->categoryArray());
        $this->set('homePageContent', $this->Product->homePageProducts($this->Category->randomCategory()));
        $categories = $this->Product->Category->find('list');
        $this->set(compact('categories'));
         $this->Product->Behaviors->attach('Containable');
         $this->Product->contain('User.username');
        $flds=array('Product.id','Product.products_thumbnailImage','Product.products_title','Product.products_views','Product.products_price','Product.products_status','DATEDIFF(products_expiredDate,now()) AS totaldays');
         if($sort==2){
            $fild='Product.products_createDate';
            $ord='DESC';
        }elseif($sort==3){
            $fild='Product.products_price';
            $ord='DESC';
        }elseif($sort==4){
            $fild='Product.products_price';
            $ord='ASC';
        }else{
             $fild='Product.products_expiredDate';
            $ord='ASC';
        }
        $prms = array(
                    'conditions'=>array(
                        'Product.category_id'=> $cat_id,
                        'OR'=>array(array('Product.products_status !='=> 'Pending'),
                        array('Product.products_status !='=> 'Disapproved')),
                        'Product.products_expiredDate >='=> date('Y-m-d H:i:s')),
                    'order' => array($fild => $ord),
                    'fields'=>$flds,
                    'contain'=>array(
                        'User.username',
                        'Approver.username'
                         )
                       );
        $this->set('products', $this->Product->find('all',$prms));
        
    }

    function browsebybrand($id=null,$type=null,$sort=null) {
        $this->layout = 'innerhome';
        $this->set('item', $this->Category->categoryArray());
        $this->set('homePageContent', $this->Product->homePageProducts($this->Category->randomCategory()));
        $categories = $this->Product->Category->find('list');
        $this->set(compact('categories'));
        $this->Product->Behaviors->attach('Containable');
        $this->Product->contain('User.username');
        $flds=array('Product.id','Product.products_thumbnailImage','Product.products_title','Product.products_views','Product.products_price','Product.products_status','DATEDIFF(products_expiredDate,now()) AS totaldays');
       $fieldtype='Product.'.$type;
       if($sort==2){
            $fild='Product.products_createDate';
            $ord='DESC';
        }elseif($sort==3){
            $fild='Product.products_price';
            $ord='DESC';
        }elseif($sort==4){
            $fild='Product.products_price';
            $ord='ASC';
        }else{
             $fild='Product.products_expiredDate';
            $ord='ASC';
        }


        $prms = array(
                    'conditions'=>array(
                        $fieldtype=> $id,
                        'OR'=>array(array('Product.products_status !='=> 'Pending'),
                        array('Product.products_status !='=> 'Disapproved')),
                        'Product.products_expiredDate >='=> date('Y-m-d H:i:s')),
                    'order' => array($fild => $ord),
                    'fields'=>$flds,
                    'contain'=>array(
                        'User.username',
                        'Approver.username'
                         )
                       );

        $this->set('products', $this->Product->find('all',$prms));
        $this->set('brandname',$this->Brand->read('brand_description',$id));

    }

    function browsebycompletedlist($type=null,$sort=null) {
        $this->layout = 'innerhome';
        $this->set('item', $this->Category->categoryArray());
        $this->set('homePageContent', $this->Product->homePageProducts($this->Category->randomCategory()));
        $categories = $this->Product->Category->find('list');
        $this->set(compact('categories'));
        $this->Product->Behaviors->attach('Containable');
        $this->Product->contain('User.username');
        $flds=array('Product.id','Product.products_thumbnailImage','Product.products_title','Product.products_views','Product.products_price','Product.products_status','DATEDIFF(products_expiredDate,now()) AS totaldays');
        if($sort==2){
            $fild='Product.products_createDate';
            $ord='DESC';
        }elseif($sort==3){
            $fild='Product.products_price';
            $ord='DESC';
        }elseif($sort==4){
            $fild='Product.products_price';
            $ord='ASC';
        }else{
             $fild='Product.products_expiredDate';
            $ord='ASC';
        }
        if($type=='all'){
        $prms = array(
                    'conditions'=>array(
                        //$fieldtype=> $id,
                        'OR'=>array(array('Product.products_status !='=> 'Pending'),
                        array('Product.products_status !='=> 'Disapproved')),
                        'Product.products_expiredDate >='=> date('Y-m-d H:i:s')),
                    'order' => array($fild => $ord),
                    'fields'=>$flds,
                    'contain'=>array(
                        'User.username',
                        'Approver.username'
                         )
                       );
        }elseif($type=='unsold'){
        $prms = array(
                    'conditions'=>array(
                        'Product.products_status'=> 'Unsold',
                        'Product.products_expiredDate >='=> date('Y-m-d H:i:s')),
                    'order' => array($fild => $ord),
                    'fields'=>$flds,
                    'contain'=>array(
                        'User.username',
                        'Approver.username'
                         )
                       );
        }elseif($type=='sold'){
        $prms = array(
                    'conditions'=>array(
                        //$fieldtype=> $id,
                        'OR'=>array(array('Product.products_status !='=> 'Pending'),
                        array('Product.products_status !='=> 'Disapproved')),
                        'Product.products_expiredDate >='=> date('Y-m-d H:i:s')),
                    'order' => array($fild => $ord),
                    'fields'=>$flds,
                    'contain'=>array(
                        'User.username',
                        'Approver.username'
                         )
                       );
        }

        $this->set('products', $this->Product->find('all',$prms));
        $this->set('type',$type);

    }

    function browsebyprice($sort=null,$price1=null,$price2=null){
        $this->layout = 'innerhome';
        $this->set('item', $this->Category->categoryArray());
        $this->set('homePageContent', $this->Product->homePageProducts($this->Category->randomCategory()));
        $categories = $this->Product->Category->find('list');
        $this->set(compact('categories'));
        $this->Product->Behaviors->attach('Containable');
        $this->Product->contain('User.username');
        $flds=array('Product.id','Product.products_thumbnailImage','Product.products_title','Product.products_views','Product.products_price','Product.products_status','DATEDIFF(products_expiredDate,now()) AS totaldays');
if($sort==2){
            $fild='Product.products_createDate';
            $ord='DESC';
        }elseif($sort==3){
            $fild='Product.products_price';
            $ord='DESC';
        }elseif($sort==4){
            $fild='Product.products_price';
            $ord='ASC';
        }else{
             $fild='Product.products_expiredDate';
            $ord='ASC';
        }
        
        if(isset ($_POST['price1'])){
           $price1=$_POST['price1'];
           $price2=$_POST['price2'];
        }

        $prms = array(
                    'conditions'=>array(
                        'Product.products_price BETWEEN ? AND ?' => array($price1, $price2),
                        'OR'=>array(array('Product.products_status !='=> 'Pending'),
                        array('Product.products_status !='=> 'Disapproved')),
                        'Product.products_expiredDate >='=> date('Y-m-d H:i:s')),
                    'order' => array($fild => $ord),
                    'fields'=>$flds,
                    'contain'=>array(
                        'User.username',
                        'Approver.username'
                         )
                       );

        $this->set('products', $this->Product->find('all',$prms));
        $this->set('price1',$price1);
        $this->set('price2',$price2);
    }

    function browsebysize($size=null,$sort=null){
        $this->layout = 'innerhome';
        $this->set('item', $this->Category->categoryArray());
	$categories = $this->Product->Category->find('list');
        $this->set(compact('categories'));
        $this->loadModel('ProductSize');
        $this->loadModel('Sizevalue');
	$productids=$this->ProductSize->find('all',array('fields'=>array('ProductSize.product_id'),'conditions'=>array('ProductSize.sizevalue_id'=>$size),'recursive'=>'-1'));
	if(!empty($productids)){
        $i=0;
        foreach($productids as $productidvalue){
            $pids[$i]=$productidvalue['ProductSize']['product_id'];
            $i++;
        }
        if($sort==2){
            $fild='Product.products_createDate';
            $ord='DESC';
        }elseif($sort==3){
            $fild='Product.products_price';
            $ord='DESC';
        }elseif($sort==4){
            $fild='Product.products_price';
            $ord='ASC';
        }else{
             $fild='Product.products_expiredDate';
            $ord='ASC';
        }
        
        $this->Product->Behaviors->attach('Containable');
        $this->Product->contain('User.username');
        $flds=array('Product.id','Product.products_thumbnailImage','Product.products_title','Product.products_views','Product.products_price','Product.products_status','DATEDIFF(products_expiredDate,now()) AS totaldays');
       $prms = array(
                    'conditions'=>array(
                        'OR'=>array(array('Product.products_status !='=> 'Pending'),
                        array('Product.products_status !='=> 'Disapproved')),
                        'Product.products_expiredDate >='=> date('Y-m-d H:i:s'),
                        'Product.id'=> $pids
                        ),
                    'order' => array($fild => $ord),
                    'fields'=>$flds,
                    'contain'=>array(
                        'User.username',
                        'Approver.username'
                         )
                       );

        $this->set('products', $this->Product->find('all',$prms));
        }
        $this->Sizevalue->recursive=-1;
		$this->set('size',$this->Sizevalue->findById($size));
    }

    function browsebycolor($colorid=null,$sort=null){
        $this->layout = 'innerhome';
        $this->set('item', $this->Category->categoryArray());
        //$this->set('homePageContent', $this->Product->homePageProducts($this->Category->randomCategory()));
        $categories = $this->Product->Category->find('list');
        $this->set(compact('categories'));
        $productidlist=$this->ProductAdditionalFieldValue->find('all',array('fields'=>array('ProductAdditionalFieldValue.product_id'),'conditions'=>array('ProductAdditionalFieldValue.values'=>$colorid),'recursive'=>'-1'));
        $productid_list = Set::extract('/ProductAdditionalFieldValue/product_id',$productidlist);
        $this->Product->Behaviors->attach('Containable');
        $this->Product->contain('User.username');
        $flds=array('Product.id','Product.products_thumbnailImage','Product.products_title','Product.products_views','Product.products_price','Product.products_status','DATEDIFF(products_expiredDate,now()) AS totaldays');
      
if($sort==2){
            $fild='Product.products_createDate';
            $ord='DESC';
        }elseif($sort==3){
            $fild='Product.products_price';
            $ord='DESC';
        }elseif($sort==4){
            $fild='Product.products_price';
            $ord='ASC';
        }else{
             $fild='Product.products_expiredDate';
            $ord='ASC';
        }
        

        $prms = array(
                    'conditions'=>array(
                        'Product.id' =>$productid_list,
                        'OR'=>array(array('Product.products_status !='=> 'Pending'),
                        array('Product.products_status !='=> 'Disapproved')),
                        'Product.products_expiredDate >='=> date('Y-m-d H:i:s')),
                    'order' => array($fild => $ord),
                    'fields'=>$flds,
                    'contain'=>array(
                        'User.username',
                        'Approver.username'
                         )
                       );

     $this->set('products', $this->Product->find('all',$prms));
     $this->set('colorid',$colorid);
    }

    function getnamebyid($id=null){
            $this->layout=null;
            $this->autoRender=false;
            $this->Category->recursive=-1;
            return $this->Category->findById($id,array('fields'=>'Category.category_name'));
    }

    function brandnamebyid($id=null){
            $this->layout=null;
            $this->autoRender=false;
            $this->Brand->recursive=-1;
            return $this->Brand->findById($id,array('fields'=>'Brand.brand_description'));
    }
    
    function report_problem($id=null){
        if(!empty($this->data)){
            $this->loadModel('Reporteditem');
            $this->Reporteditem->save($this->data['Reporteditem']);
        }
        $this->ask_a_question($id);        
    }

    function backstage_reported_items(){
        $this->layout='admin';
        $this->loadModel('Reporteditem');
        $this->Reporteditem->Behaviors->attach('Containable');
        $this->paginate = array('limit' => 25,
                    'order' => array('Reporteditem.id' => 'desc'),
                    'contain'=>array(
                        'Product.id','Product.products_thumbnailImage','Product.products_title','Product.user_id','Product.User.username','Reporter.username'
                         )
                 );
        $this->set('products', $this->paginate('Reporteditem'));
    }

     function backstage_salesreview(){
        $this->layout='adminsales';
        $this->loadModel('Order');
        $this->Order->Behaviors->attach('Containable');
        $this->Order->bindModel(
                array('belongsTo' => array(
                        'Seller' => array(
                            'className' => 'User',
                            'foreignKey' => 'seller_id'
                        ),
                        'Product' => array(
                            'className' => 'Product',
                            'foreignKey' => 'product_id'
                        ),
                    'User' => array(
                            'className' => 'User',
                            'foreignKey' => 'user_id'
                        )
                    )
                )
        );
        if(!empty($_POST)){
        $reports = $this->Order->find('all',
         array('fields' => array('Order.id','Order.quantity','Order.product_cost','Order.user_id','Order.add_date'),
             'contain'=>array(
                        'Product.id','Product.products_title','User.username','Seller.username'
                         ),
         'conditions'=>array('Order.add_date BETWEEN ? AND ?' =>
          array(date('Y-m-d',  strtotime($_POST['start'])), date('Y-m-d',  strtotime($_POST['end'])))),
          'order'=>'Order.id asc'));
          $this->set('reports',$reports);
          $totalproduct = $this->Order->find('all', array('fields' =>
          array('Order.id','sum(Order.quantity) as tquantity'),
          'conditions'=>array('Order.add_date BETWEEN ? AND ?' =>
           array(date('Y-m-d',  strtotime($_POST['start'])), date('Y-m-d',  strtotime($_POST['end']))))));
          $this->set('totalproduct',$totalproduct);
          $totalbuyers = $this->Order->find('all',
          array('fields' => array('Order.id','count(DISTINCT Order.user_id) as totalbuyer'),
              'conditions'=>array('Order.add_date BETWEEN ? AND ?' =>
              array(date('Y-m-d',  strtotime($_POST['start'])), date('Y-m-d',  strtotime($_POST['end']))))));
        $this->set('totalbuyers', $totalbuyers);
        $totalseller = $this->Order->find('all',
          array('fields' => array('Order.id','count(DISTINCT Order.seller_id) as totalseller'),
              'conditions'=>array('Order.add_date BETWEEN ? AND ?' =>
              array(date('Y-m-d',  strtotime($_POST['start'])), date('Y-m-d',  strtotime($_POST['end']))))));
        $this->set('totalseller', $totalseller);
        $totalsales = $this->Order->find('all',
     array('fields' => array('Order.id','sum(Order.quantity * Order.product_cost) as totalsale'),
         'conditions'=>array('Order.add_date BETWEEN ? AND ?' =>
         array(date('Y-m-d',  strtotime($_POST['start'])), date('Y-m-d',  strtotime($_POST['end']))))));
        $this->set('totalsales', $totalsales);
        $this->set('startdate', $_POST['start']);
        $this->set('enddate', $_POST['end']);
        }else{
            $reports=null;
            $this->set('reports',$reports);
        }
         
    }

    function contact_seller($id){
        $this->ask_a_question($id);
    }

    function store($id){
        $this->layout = 'innerhome';
        //left navigation
        $this->set('item', $this->Category->categoryArray());
        $this->Product->Behaviors->attach('Containable');
        $this->Product->contain('Category');
        $allProducts=$this->Product->find('all', array('conditions'=>array('OR'=>array(array('Product.products_status'=>'Active'),array('Product.products_status'=>'Approved')), 'Product.products_expiredDate >='=>date("Y-m-d H:i:s"), 'Product.user_id'=>$id)));
        $this->set('sellerProducts', $this->Product->store($allProducts));
    }

    function negotiate($pid=null, $flag=null) {
        $this->layout = false;
        $this->set('pid',$pid);
        $this->loadModel('Negotiation');
        if (!empty($this->data)) {
            $this->Product->recursive=-1;
            $productinfo = $this->Product->findById($this->data['Negotiation']['product_id'], array('Product.id','Product.products_offerAcceptLeastPrice'));
            if(($productinfo['Product']['products_offerAcceptLeastPrice']>0) AND ($productinfo['Product']['products_offerAcceptLeastPrice']<=$this->data['Negotiation']['last_offer'])){
            $this->data['Negotiation']['status'] = 'Accepted';
           
            }else{
            $this->data['Negotiation']['status'] = 'Pending';
           
            }
            $this->data['Negotiation']['buyer_id'] = $this->Auth->user('id');
            $this->Negotiation->save($this->data['Negotiation']);
            $this->render('negotiate_status1');
        }
        if($flag==null){
        $limitchk = $this->Negotiation->find('count', array('conditions' => array('Negotiation.buyer_id' => $this->Auth->user('id'), 'Negotiation.product_id' => $pid)));
        if ($limitchk >= 3) {
            $this->render('negotiate_limit');
        } else {

            $statuschk = $this->Negotiation->find('first',
                            array('conditions' => array('Negotiation.buyer_id' => $this->Auth->user('id'), 'Negotiation.product_id' => $pid),
                                'order' => array('Negotiation.id DESC'), 'recursive' => -1));
            if ($statuschk['Negotiation']['status'] == 'Pending') {
                $this->render('negotiate_status1');
            } elseif ($statuschk['Negotiation']['status'] == 'Rejected') {
                $this->render('negotiate_status');
            } elseif ($statuschk['Negotiation']['status'] == 'Accepted') {
                $this->render('negotiate_status2');
            }
        }
        }
        $limitchk = $this->Negotiation->find('count', array('conditions' => array('Negotiation.buyer_id' => $this->Auth->user('id'), 'Negotiation.product_id' => $pid)));
        if ($limitchk >= 3) {
            $this->render('negotiate_limit');
        }
        $history = $this->Negotiation->find('all', array('conditions' => array('Negotiation.buyer_id' => $this->Auth->user('id'), 'Negotiation.product_id' => $pid),'recursive' => -1));
        $this->set('history', $history);
        $this->Product->Behaviors->attach('Containable');
        $this->Product->contain('User.username');
        $productinfo = $this->Product->findById($pid, array('Product.id','Product.products_offerDeclineLowerPrice'));
        $this->set('productinfo', $productinfo);
        if($flag==2){
            $pendinginfo = $this->Negotiation->find('first',
                            array('conditions' => array('Negotiation.buyer_id' => $this->Auth->user('id'), 'Negotiation.product_id' => $pid, 'Negotiation.status' =>'Pending'),
                                'order' => array('Negotiation.id DESC'), 'recursive' => -1));
            $this->set('pendinginfo', $pendinginfo);
        }
        $this->set('flag', $flag);
    }


    function negotiation_accepted(){
             $this->loadModel('Negotiation');
             if($this->Session->read('grouptype')=='Buyers'){
             $this->paginate = array('limit' => 25,
                    'conditions'=>array(
                        'Negotiation.status'=> 'Accepted','Negotiation.buyer_id'=> $this->Auth->user('id')),
                    'fields'=>array('Product.id','Product.products_thumbnailImage','Product.products_title','Product.user_id','Product.products_price','Negotiation.last_offer','Negotiation.cart_chk','User.username')
                     );
             }elseif($this->Session->read('grouptype')=='Sellers'){
                 $this->paginate = array('limit' => 25,
                    'conditions'=>array(
                        'Negotiation.status'=> 'Accepted','Negotiation.seller_id'=> $this->Auth->user('id')),
                    'fields'=>array('Product.id','Product.products_thumbnailImage','Product.products_title','Product.user_id','Product.products_price','Negotiation.id','Negotiation.last_offer','Negotiation.buyer_id','Negotiation.cart_chk','Buyer.username')
                     );
             }
		$this->set('products', $this->paginate('Negotiation'));
                $this->layout="innerhome";
            }

  function negotiation_pending() {
        $this->loadModel('Negotiation');
        if ($this->Session->read('grouptype') == 'Buyers') {
            $this->paginate = array('limit' => 25,
                'conditions' => array(
                    'Negotiation.status' => 'Pending', 'Negotiation.buyer_id' => $this->Auth->user('id')),
                'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.products_price', 'Negotiation.last_offer', 'Negotiation.cart_chk', 'User.username')
            );
        } elseif ($this->Session->read('grouptype') == 'Sellers') {
            $this->paginate = array('limit' => 25,
                'conditions' => array(
                    'Negotiation.status' => 'Pending', 'Negotiation.seller_id' => $this->Auth->user('id')),
                'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.products_price', 'Negotiation.id', 'Negotiation.last_offer', 'Negotiation.buyer_id', 'Negotiation.cart_chk', 'Buyer.username')
            );
        }
        $this->set('products', $this->paginate('Negotiation'));
        $this->layout = "innerhome";
    }

  function negotiation_rejected() {
        $this->loadModel('Negotiation');
        if ($this->Session->read('grouptype') == 'Buyers') {
            $this->paginate = array('limit' => 25,
                'conditions' => array(
                    'Negotiation.status' => 'Rejected', 'Negotiation.buyer_id' => $this->Auth->user('id')),
                'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.products_price', 'Negotiation.last_offer', 'Negotiation.cart_chk', 'Negotiation.id', 'User.username'),
                'order' => array(
                    'Negotiation.id' => 'desc'
                )
            );
        } elseif ($this->Session->read('grouptype') == 'Sellers') {
            $this->paginate = array('limit' => 25,
                'conditions' => array(
                    'Negotiation.status' => 'Rejected', 'Negotiation.seller_id' => $this->Auth->user('id')),
                'fields' => array('Product.id', 'Product.products_thumbnailImage', 'Product.products_title', 'Product.user_id', 'Product.products_price', 'Negotiation.id', 'Negotiation.last_offer', 'Negotiation.buyer_id', 'Negotiation.cart_chk', 'Buyer.username')
            );
        }

        $this->set('products', $this->paginate('Negotiation'));
        $this->layout = "innerhome";
    }

    function getnegotiation($pid=null, $bid=null) {
        $this->loadModel('Negotiation');
        if ($bid == null) {
            return $this->Negotiation->find('all', array('conditions' => array('Negotiation.buyer_id' => $this->Auth->user('id'), 'Negotiation.product_id' => $pid), 'recursive' => -1));
        } else {
            return $this->Negotiation->find('all', array('conditions' => array('Negotiation.buyer_id' => $bid, 'Negotiation.seller_id' => $this->Auth->user('id'), 'Negotiation.product_id' => $pid), 'recursive' => -1));
        }
    }

    function delete_negotiation($pid=null) {
        $this->autoRender = false;
        $this->layout = false;
        $this->loadModel('Negotiation');
        $conditions = array('Negotiation.buyer_id' => $this->Auth->user('id'), 'Negotiation.product_id' => $pid);
        $this->Negotiation->deleteAll($conditions);
    }

    function reject_negotiate($nid=null) {
        $this->layout = false;
        if (!empty($this->data)) {
        $this->loadModel('Negotiation');
        $this->data['Negotiation']['status']='Rejected';
        $this->Negotiation->save($this->data['Negotiation']);
         $this->render('reject_msg');
        }
        $this->set('nid',$nid);
    }

    function accept_negotiate($nid=null) {
        $this->layout = false;
        if (!empty($this->data)) {
        $this->loadModel('Negotiation');
        $this->data['Negotiation']['status']='Accepted';
        $this->Negotiation->save($this->data['Negotiation']);
         $this->render('reject_msg1');
        }
        $this->set('nid',$nid);
    }

    function sold(){
		$this->Product->recursive=-1;
		$seller_products=$this->Product->find("list",array('conditions'=>array("Product.user_id"=>$this->Auth->user('id')),'fields'=>array('Product.id')));
		$conditions=array('Cart.product_id'=>$seller_products,'Cart.order_id >'=>0,'Cart.payment_status'=>1);
		$orders=array("Cart.add_date"=>"DESC");
		$total=$this->Cart->find("count",array("conditions"=>$conditions));		
		$sum=$this->Cart->find("first",array("conditions"=>$conditions,'fields' => array('sum((Cart.product_cost*Cart.quantity)+Cart.sales_tax+Cart.shipping_cost) AS total')));
		$this->Cart->Behaviors->attach('Containable');
		$this->Cart->contain('Order.id','Order.transaction_id','Shipping.shipping_method',
		'Product.id','Product.user_id','Product.category_id','Product.products_title','Product.products_thumbnailImage','Product.User.first_name','Product.User.last_name','User.id','User.first_name','User.last_name');
		$this->paginate=array('limit' => 10,"conditions"=>$conditions,"order"=>$orders);		
		$this->set('solds', $this->paginate('Cart'));
		$this->set(compact('total','sum'));
        $this->layout="innerhome";
	}
	
	function search_sold(){	    
		$this->layout=FALSE;
        $this->Product->recursive=-1;		
		$seller_products=$this->Product->find("list",array('conditions'=>array("Product.user_id"=>$this->Auth->user('id'), $key=>$value),'fields'=>array('Product.id')));
		$this->Cart->Behaviors->attach('Containable');
		if($this->data){
			if($this->data["search_by"]==""){
				$this->autoRender=FALSE;
				echo '<br /><br /><h2>Please Choose an option from dropdown</h2>';				
				return;
			}
			if($this->data["search_by"]=="buyer_id"){
				$conditions=array("Cart.user_id"=>$this->data["keywords"]);
			}
			else{
				if($this->data["search_by"]=="item_title"){
					$conditions=array("Product.products_title LIKE"=>"%".$this->data["keywords"]."%");					
				}
				if($this->data["search_by"]=="item_number"){
					$conditions=array("Product.id"=>$this->data["keywords"]);
				}
			}
			$total=$this->Cart->find("count",array("conditions"=>$conditions));		
			$sum=$this->Cart->find("first",array("conditions"=>$conditions,'fields' => array('sum(Cart.product_cost*Cart.quantity) AS total')));
			$this->Cart->Behaviors->attach('Containable');
			$this->Cart->contain('Order.id','Order.transaction_id','Shipping.shipping_method',
			'Product.id','Product.user_id','Product.category_id','Product.products_title','Product.products_thumbnailImage','Product.User.first_name','Product.User.last_name','User.id','User.first_name','User.last_name');
			$this->paginate=array('limit' => 10,"conditions"=>$conditions,"order"=>$orders);		
			$this->set('solds', $this->paginate('Cart'));
			$this->set(compact('total','sum'));

		}
	}	
	
	function add_tracking($id=null){
		$this->layout=false;
		$this->loadModel('Order');
		if (!empty($this->data)) {
			$this->Order->save($this->data);
			$this->Session->setFlash(__('Tracking ID has been updated successfully.', true));					
			$this->render('success');
		}
		$this->Order->recursive=-1;
		$transaction_id=$this->Order->findById($id,array('fields'=>"Order.id,Order.transaction_id"));
		$this->set('transaction_id', $transaction_id);
	}
	
	function contact_buyer($id=null){
		$this->layout = false;
		$this->loadModel('Order');                 
         $this->Order->bindModel(
                array('belongsTo' => array(
                        'Seller' => array(
                            'className' => 'User',
                            'foreignKey' => 'seller_id'
                        ),
                        'Product' => array(
                            'className' => 'Product',
                            'foreignKey' => 'product_id'
                        ),
                    'User' => array(
                            'className' => 'User',
                            'foreignKey' => 'user_id'
                        )
                    )
                )
        );
		if (!empty($this->data)) {
			$this->loadModel('Message');
			$this->loadModel('MessageTrack');
			$this->Message->create();
				if ($this->Message->save($this->data)) {
					$mid=$this->Message->getLastInsertID();
					/////////for sent item//////									
					$this->data['MessageTrack']['message_id']=$mid;										
					$this->data['MessageTrack']['msg_type']=0;
					$this->data['MessageTrack']['read']=0;
					$this->data['MessageTrack']['star']=0;					
					$this->MessageTrack->save($this->data);
					///////////for inbox///////					
					 $this->data['MessageTrack']['id']=null;
					$this->data['MessageTrack']['message_id']=$mid;					
					$this->data['MessageTrack']['msg_type']=1;
					$this->data['MessageTrack']['read']=0;
					$this->data['MessageTrack']['star']=0;					
					$this->MessageTrack->save($this->data);
					$this->Session->setFlash(__('The message has been sent successfully.', true));
					$this->render("success");
				}else{
				 $this->Session->setFlash(__('The message could not be sent. Please, try again.', true));				
				}
		}
		$this->Order->recursive=-1;
		$this->Order->Behaviors->attach('Containable');	
		$qData=$this->Order->find("all",array(
			'conditions'=>array('Order.product_id'=>$id),			
			'contain'=>array('User.id','User.first_name','User.last_name','Product.id','Product.products_title','Product.user_id','Product.products_price','Product.products_expiredDate','Product.products_thumbnailImage')
		));

		$this->set('qData', $qData);
	}

   function create_dispute($pid=null,$cid=null){
            $this->layout=FALSE;
            $this->loadModel('Dispute');
             if(!empty($this->data)) {
                 
              $this->data['Dispute']['disputer_id']=$this->Auth->user('id');
               $this->data['Dispute']['expire_date']=date('Y-m-d', strtotime('+45 days'));
               $this->data['Dispute']['open_date']=date('Y-m-d');
               $this->data['Dispute']['status']='Pending Mediation';

              $chkext=$this->Dispute->find('count', array('conditions' => array('Dispute.seller_id' =>$this->data['Dispute']['seller_id'],'Dispute.disputer_id' =>$this->Auth->user('id'),'Dispute.product_id' =>$this->data['Dispute']['product_id'])));
              if($chkext==0){
            if($data = $this->Uploader->uploadAll()) {
               if(!empty ($data['image1']['name'])){
              $this->data['Dispute']['image1']=$data['image1']['name'];              
                }
                if(!empty ($data['image2']['name'])){
               $this->data['Dispute']['image2']=$data['image2']['name'];               
                    }
               $this->Dispute->save($this->data['Dispute']);
               }else{
                   $this->data['Dispute']['image1']='';
                   $this->data['Dispute']['image2']='';
                  $this->Dispute->save($this->data['Dispute']);
               }

               $this->render('dispute_success');
                }else{
                 $this->render('dispute_already');
                }
             }
            //$this->Product->recursive = 1;
            $this->Cart->Behaviors->attach('Containable');
            $this->Cart->contain('User.username');
			$conditions=array("Product.id"=>$pid,"Cart.id"=>$cid);
			$contains=array('Product.id','Product.products_title','Product.user_id');
            $productinfo=  $this->Cart->find("first",array('conditions'=>$conditions,'contain'=>$contains));
           	$this->set('productinfo',$productinfo);
        }

    function seller_dispute(){
        $this->layout="innerhome";
          $this->loadModel('Dispute');
          $this->Dispute->Behaviors->attach('Containable');
            $this->Dispute->contain('Disputer.username');
       $disputelist=$this->Dispute->find('all', array('conditions' => array('Dispute.seller_id' =>$this->Auth->user('id'))));
        $this->set('disputelist',$disputelist);

    }

    function viewdispute($id=null){
        $this->layout=null;
          $this->loadModel('Dispute');
          $this->Dispute->Behaviors->attach('Containable');
            $this->Dispute->contain('Disputer.username','Product');
        $this->set('disputelist',$this->Dispute->find('first', array('conditions' => array('Dispute.id' =>$id))));

    }

    function buyer_dispute(){
        $this->layout="innerhome";
          $this->loadModel('Dispute');
          $this->Dispute->Behaviors->attach('Containable');
            $this->Dispute->contain('Seller.username');
       $disputelist=$this->Dispute->find('all', array('conditions' => array('Dispute.disputer_id' =>$this->Auth->user('id'))));
       $this->set('disputelist',$disputelist);

    }

     function backstage_sadmin_dispute(){
        $this->layout="admin";
          $this->loadModel('Dispute');
          $this->Dispute->Behaviors->attach('Containable');
            $this->Dispute->contain('Seller.username');
       $disputelist=$this->Dispute->find('all', array('conditions' => array('Dispute.disputer_id' =>$this->Auth->user('id'))));
        $this->set('disputelist',$disputelist);

    }

    function close_dispute($id=null){
        $this->layout=false;
        $this->autoRender=false;
        $this->loadModel('Dispute');
        $this->Dispute->id=$id;
        $this->Dispute->saveField('status', 'Resolved');
        
    }

    function mediation_dispute($id=null){
        $this->layout=false;
        $this->autoRender=false;
        $this->loadModel('Dispute');
        $this->Dispute->id=$id;
        $this->Dispute->saveField('involved_sadmin', '1');
        $this->Dispute->id=$id;
        $this->Dispute->saveField('status', 'Pending Mediation');

    }

  function addnote_dispute($id=null){
        $this->layout = false;
        $this->loadModel('Disputenote');
        if (!empty($this->data)) {
            $this->data['Disputenote']['user_id'] = $this->Auth->user('id');
            $this->Disputenote->save($this->data);
             $this->Session->setFlash(__('The Note has been added Successfully.', true));
            $this->Render('success');
        } else {
            $this->set('id', $id);
        }
    }

    function getdisputenote($id=null){
		$this->layout = false;
		$this->autoRender=false;
                $this->loadModel('Disputenote');
		return $this->Disputenote->find('all', array('conditions' => array('Disputenote.case_id' => $id,'Disputenote.user_id' => $this->Auth->user('id'))));
   }

   function monthly_sales_report(){
       $this->layout = 'homereport';
        $chk='www';
         $this->loadModel('Order');
         $this->Order->bindModel(
                array('belongsTo' => array(
                        'Seller' => array(
                            'className' => 'User',
                            'foreignKey' => 'seller_id'
                        ),
                        'Product' => array(
                            'className' => 'Product',
                            'foreignKey' => 'product_id'
                        ),
                    'User' => array(
                            'className' => 'User',
                            'foreignKey' => 'user_id'
                        )
                    )
                )
        );

       if(isset ($_POST['start'])){
      $previousweek = $this->Order->find('first', array('fields' => array('Order.id','sum(Order.quantity * Order.product_cost) as totalsale','Order.add_date','DATE_FORMAT(add_date,"%u") as week'),'conditions'=>array('Order.add_date <' => date('Y-m-d',  strtotime($_POST['start'])),'Order.seller_id'=>$this->Auth->User('id')),'recursive'=>'-1','order'=>'Order.add_date desc','group'=>'week'));
       if(empty($previousweek)){
           $previousweek =0;         
       }else{
         $previousweek =$previousweek[0]['totalsale'];         
       }
       $this->set('previousweek', $previousweek);
        $totalproduct = $this->Order->find('all', array('fields' => array('Order.id','Order.add_date','sum(Order.quantity) as tquantity','DATE_FORMAT(add_date,"%u") as week'),'conditions'=>array('Order.add_date BETWEEN ? AND ?' => array(date('Y-m-d',  strtotime($_POST['start'])), date('Y-m-d',  strtotime($_POST['end']))),'Order.seller_id'=>$this->Auth->User('id')),'recursive'=>'-1','order'=>'week asc','group'=>'week'));
        $totalbuyers = $this->Order->find('all', array('fields' => array('Order.id','count(DISTINCT Order.user_id) as totalbuyer','DATE_FORMAT(add_date,"%u") as week'),'conditions'=>array('Order.add_date BETWEEN ? AND ?' => array(date('Y-m-d',  strtotime($_POST['start'])), date('Y-m-d',  strtotime($_POST['end']))),'Order.seller_id'=>$this->Auth->User('id')),'recursive'=>'-1','order'=>'week asc','group'=>'week'));
        $this->set('totalbuyers', $totalbuyers);
        $totalsales = $this->Order->find('all', array('fields' => array('Order.id','sum(Order.quantity * Order.product_cost) as totalsale','DATE_FORMAT(add_date,"%u") as week'),'conditions'=>array('Order.add_date BETWEEN ? AND ?' => array(date('Y-m-d',  strtotime($_POST['start'])), date('Y-m-d',  strtotime($_POST['end']))),'Order.seller_id'=>$this->Auth->User('id')),'recursive'=>'-1','order'=>'week asc','group'=>'week'));
        $this->set('totalsales', $totalsales);
        $this->set('startdate', $_POST['start']);
        $this->set('enddate', $_POST['end']);

       }else{
           $totalproduct=null;
           $chk='authentic';
           
       }
        $this->set('totalproduct', $totalproduct);
        $this->set('chk', $chk);
   }


    function admin_monthly_sales_report(){
       $this->layout = 'homereport';
        $chk='www';
        if(isset ($_POST['start'])){
       $this->loadModel('Order');
       $previousweek = $this->Order->find('first', array('fields' => array('Order.id','sum(Order.quantity * Order.product_cost) as totalsale','Order.add_date','DATE_FORMAT(add_date,"%u") as week'),'conditions'=>array('Order.add_date <' => date('Y-m-d',  strtotime($_POST['start']))),'recursive'=>'-1','order'=>'Order.add_date desc','group'=>'week'));
        if(empty($previousweek)){
           $previousweek =0;
       }else{
         $previousweek =$previousweek[0]['totalsale'];

       }
       $this->set('previousweek', $previousweek);
        $totalproduct = $this->Order->find('all', array('fields' => array('Order.id','Order.add_date','sum(Order.quantity) as tquantity','DATE_FORMAT(add_date,"%u") as week'),'conditions'=>array('Order.add_date BETWEEN ? AND ?' => array(date('Y-m-d',  strtotime($_POST['start'])), date('Y-m-d',  strtotime($_POST['end'])))),'recursive'=>'-1','order'=>'week asc','group'=>'week'));
        $totalbuyers = $this->Order->find('all', array('fields' => array('Order.id','count(DISTINCT Order.user_id) as totalbuyer','DATE_FORMAT(add_date,"%u") as week'),'conditions'=>array('Order.add_date BETWEEN ? AND ?' => array(date('Y-m-d',  strtotime($_POST['start'])), date('Y-m-d',  strtotime($_POST['end'])))),'recursive'=>'-1','order'=>'week asc','group'=>'week'));
        $this->set('totalbuyers', $totalbuyers);
        $totalsales = $this->Order->find('all', array('fields' => array('Order.id','sum(Order.quantity * Order.product_cost) as totalsale','DATE_FORMAT(add_date,"%u") as week'),'conditions'=>array('Order.add_date BETWEEN ? AND ?' => array(date('Y-m-d',  strtotime($_POST['start'])), date('Y-m-d',  strtotime($_POST['end'])))),'recursive'=>'-1','order'=>'week asc','group'=>'week'));
        $this->set('totalsales', $totalsales);
        $this->set('startdate', $_POST['start']);
        $this->set('enddate', $_POST['end']);

       }else{
           $totalproduct=null;
           $chk='authentic';

       }
        $this->set('totalproduct', $totalproduct);
        $this->set('chk', $chk);
   }

   function orderdetails($startdate=null,$enddate=null,$weekno=null){
       $this->layout=false;
       $this->autoRender=false;
       $this->loadModel('Order');
       //$this->Order->recursive = 2;
       return $this->Order->find('all', array('fields' => 
           array('Order.id','Order.quantity','Order.product_cost','Order.user_id','Product.products_thumbnailImage'
               ,'Product.products_title','Product.id','User.username','Order.add_date','Order.transaction_id'),
           'conditions'=>array('Order.add_date BETWEEN ? AND ?' => array(date('Y-m-d',  strtotime($startdate)),
               date('Y-m-d',  strtotime($enddate))),'DATE_FORMAT(add_date,"%u")'=>$weekno),'order'=>'Order.user_id asc'));
   }

   function delete_reportitem($id=null){
            $this->layout=FALSE;
            $this->loadModel('Reporteditem');
            //$this->Reportnote->id=$id;
            $this->Reporteditem->delete($id);
            $this->autoRender=false;
   }

function generatereport($startdate=null,$enddate=null)
{
$this->layout = null;
$this->autoLayout = false;
$this->loadModel('Order');
$this->Order->Behaviors->attach('Containable');
$reports = $this->Order->find('all',
         array('fields' => array('Order.id','Order.quantity','Order.product_cost','Order.user_id','Order.add_date'),
             'contain'=>array(
                        'Product.id','Product.products_title','User.username','Seller.username'
                         ),
         'conditions'=>array('Order.add_date BETWEEN ? AND ?' =>
          array(date('Y-m-d',  $startdate), date('Y-m-d',  $enddate))),
          'order'=>'Order.id asc'));
          
$this->set('reports',$reports);
}

function brand_menu($type=null){
	$this->layout=null;
	$this->autoRender=false;
	//$type='global_brands';

	$this->Product->Behaviors->attach('Containable');
	if($type=='global_brands'){
	return $this->Product->find('all', array('fields' =>
		array('Product.id','count(Product.'.$type.') as totalproduct'),
		'conditions'=>array('Product.products_expiredDate >='=> date('Y-m-d H:i:s'),'OR'=>array(array('Product.products_status !='=>'Disapproved'),array('Product.products_status !='=>'Pending'))),
		'contain'=>array('Brand.id','Brand.brand_description'),
		'order'=>'totalproduct desc','group'=>'Product.'.$type,'limit'=>5));
	}
	if($type=='global_conditions'){
	return $this->Product->find('all', array('fields' =>
		array('Product.id','count(Product.'.$type.') as totalproduct'),
		'conditions'=>array('Product.products_expiredDate >='=> date('Y-m-d H:i:s'),'OR'=>array(array('Product.products_status !='=>'Disapproved'),array('Product.products_status !='=>'Pending'))),
		'contain'=>array('ProductCondition.id','ProductCondition.brand_description'),
		'order'=>'totalproduct desc','group'=>'Product.'.$type));
	}

	if($type=='global_styles'){
	return $this->Product->find('all', array('fields' =>
		array('Product.id','count(Product.'.$type.') as totalproduct'),
		'conditions'=>array('Product.products_expiredDate >='=> date('Y-m-d H:i:s'),'OR'=>array(array('Product.products_status !='=>'Disapproved'),array('Product.products_status !='=>'Pending'))),
		'contain'=>array('ProductStyle.id','ProductStyle.brand_description'),
		'order'=>'totalproduct desc','group'=>'Product.'.$type));
	}
	
}

function gallery_popup($id=null){
	$this->layout=null;
	$this->Product->recursive=-1;	
	$thumb=$this->Product->findById($id);
	$this->ProductImage->recursive=-1;
	$images=$this->ProductImage->find("all",array("conditions"=>array("ProductImage.product_id"=>$id),"order"=>array("ProductImage.id"=>"desc")));	
	$this->set(compact('thumb', 'images'));
}

function size_menu(){
    $this->layout=null;
    $this->autoRender=false;
    $this->loadModel('Sizevalue');
    
    $allsizes=$this->Sizevalue->find('all',array('order'=>'Sizevalue.size_value  asc','group'=>'Sizevalue.size_value','recursive'=>'-1'));
    $i=0;
    foreach($allsizes as  $allsizevalue){    
    $sizeproductcount=$this->ProductSize->find('count',array('conditions'=>array('ProductSize.sizevalue_id'=>$allsizevalue['Sizevalue']['id']),'recursive'=>'-1'));
        if($sizeproductcount>0){
        $sizemenu[$i]=$allsizevalue['Sizevalue']['id'].'@'.$allsizevalue['Sizevalue']['size_value'];
   
        $i++;
    }
  }
    return $sizemenu;
}

function color_menu(){
    $this->layout=null;
    $this->autoRender=false;
    $this->loadModel('Field');
    $color=$this->Field->find('all',array('fields'=>array('Field.id'),'conditions'=>array('Field.field_name'=>'Color'),'order'=>'Field.id  asc','recursive'=>'-1'));
	$results = Set::extract('/Field/id', $color);    
	return $this->ProductAdditionalFieldValue->find('all',array('fields'=>array('ProductAdditionalFieldValue.values','count(ProductAdditionalFieldValue.values) as totalproduct'),'conditions'=>array('ProductAdditionalFieldValue.field_id'=>$results),'order'=>'ProductAdditionalFieldValue.values  asc','group'=>'ProductAdditionalFieldValue.values','recursive'=>'-1'));
}

 function autobrand($id=null,$type=null) {
        Configure::write('debug', 0);
        $this->layout = 'ajax';
        $this->recursive = 0;
        
        $conditions=array('Categorybrand.category_id'=>$id,'Categorybrand.brand_type'=>$type,'Brand.brand_description LIKE' => $this->params['url']['q'] . '%');
        $order=array('Brand.brand_description' => 'asc');
        $brands=$this->Categorybrand->find('all',array('conditions'=>$conditions,'order'=>$order));
	$this->set('brands', $brands);
    }
}
?>